📜  Python MySQL – GROUP BY 和 HAVING 子句

📅  最后修改于: 2022-05-13 01:55:11.190000             🧑  作者: Mango

Python MySQL – GROUP BY 和 HAVING 子句

在本文中,我们将看到如何使用Python对 SQL 执行 groupby() 和 HAVING() 操作。在这里,我们将考虑一个大学数据库,根据学生实力对部门进行分组操作。

通过...分组

GROUP BY 语句根据使用的聚合函数将具有相同值的行分组为单个。聚合函数是 (COUNT(), MAX(), MIN(), SUM(), AVG())。

使用中的数据库:

例子:

Python3
# Establish connection to MySQL database
import mysql.connector 
  
database = mysql.connector.connect( 
    host="localhost", 
    user="root", 
    password="", 
    database="sravan"
) 
  
# Creating cursor object
cur_object = database.cursor() 
  
# Execute the query 
find = "SELECT  department,sum(strength) from \
college_data GROUP BY(department)";
cur_object.execute(find) 
  
# fetching all results
data = cur_object.fetchall() 
print("Total departments with count : ")
print(" ")
for res in data: 
    print(res[0],res[1],sep="--") 
  
# Close database connection 
database.close()


Python3
# Establish connection to MySQL database
import mysql.connector 
  
# give connection with xampp
database = mysql.connector.connect( 
    host="localhost", 
    user="root", 
    password="", 
    database="sravan"
) 
  
# Creating cursor object
cur_object = database.cursor() 
  
find = "SELECT  department,sum(strength) from college_data\
GROUP BY(department) HAVING sum(strength)<=400 ";
  
# Execute the query 
cur_object.execute(find) 
  
# fetching all results
data = cur_object.fetchall() 
print("Total departments with count less than 400 : ")
print(" ")
for res in data: 
    print(res[0],res[1],sep="--") 
  
# Close database connection 
database.close()


输出:

按拥有分组

拥有子句基本上就像带有 GROUP BY 子句的聚合函数。使用 HAVING 子句代替 WHERE 与聚合函数。而 GROUP BY 子句将具有相同值的行分组为汇总行。 have 子句与 where 子句一起使用,以查找具有特定条件的行。 have 子句总是在 Group By 子句之后使用。

使用中的数据库:

例子:

蟒蛇3

# Establish connection to MySQL database
import mysql.connector 
  
# give connection with xampp
database = mysql.connector.connect( 
    host="localhost", 
    user="root", 
    password="", 
    database="sravan"
) 
  
# Creating cursor object
cur_object = database.cursor() 
  
find = "SELECT  department,sum(strength) from college_data\
GROUP BY(department) HAVING sum(strength)<=400 ";
  
# Execute the query 
cur_object.execute(find) 
  
# fetching all results
data = cur_object.fetchall() 
print("Total departments with count less than 400 : ")
print(" ")
for res in data: 
    print(res[0],res[1],sep="--") 
  
# Close database connection 
database.close() 

输出: