聚合函数 COUNT / SUM / AVG / MAX / MIN
57.16 聚合函数 COUNT / SUM / AVG / MAX / MIN
COUNT(*) 或 COUNT(列) 统计行数;COUNT(列) 忽略 NULL。
SUM(列) 求和;AVG(列) 平均值;MAX/MIN 最大/最小。
通常与 WHERE 联用:WHERE class_name='一班' 再 AVG(score)。
- COUNT(*) — 总行数
- SUM(score) — 分数总和
- AVG(score) — 平均分
- MAX(score) / MIN(score) — 最高/最低分
全班与分班统计
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='py_demo', charset='utf8mb4')
try:
with conn.cursor() as cur:
cur.execute('''
SELECT COUNT(*) AS cnt,
SUM(score) AS total,
AVG(score) AS avg_score,
MAX(score) AS best,
MIN(score) AS worst
FROM students
''')
print('总体:', cur.fetchone())
cur.execute(
'SELECT AVG(score) FROM students WHERE class_name=%s', ('一班',)
)
print('一班平均分:', round(cur.fetchone()[0], 1))
finally:
conn.close()