一、簡單使用
sum:求和(一般用于處理數值型)
avg:平均(一般用于處理數值型)
max:最大(也可以用于處理字符串和日期)
min:最小(也可以用于處理字符串和日期)
count:數量(統計非空值的數據個數)
以上分組函數都忽略空null值的數據
1
2
|
select sum (salary) as 和, avg (salary) as 平均, max (salary) as 最大, min (salary) as 最小, count (salary) as 數量 from employees; |
二、搭配distinct去重
(以上函數均可)
1
2
|
select sum ( distinct salary) as 和, avg ( distinct salary) as 平均, count ( distinct salary) as 去重數量, count (salary) as 不去重數量 from employees; |
三、count()詳細介紹
1
2
3
|
#相當于統計行數方式一 select count (*) from employees; |
1
2
3
|
#相當于統計行數方式二,其中1可以用其他常量或字段替換 select count (1) from employees; |
效率問題:
myisam存儲引擎下,count(*)
的效率高
innodb存儲引擎下,count(*)
和count(1)
的效率差不多,比count(字段)
高
因此一般用count(*)
統計行數
四、分組查詢
1
2
3
4
5
6
|
#其中[]內為可選 select 分組函數,列表(要求出現在 group by 的后面) from 表 [ where 篩選條件] group by 分組列表 [ order by 子句] |
示例:
1
2
3
4
|
#查詢每個工種的最高工資 select max (salary) as 最高工資,job_id from employees group by job_id; |
1
2
3
4
5
|
#查詢每個部門中,郵箱包含a的員工的平均工資(分組前的篩選) select avg (salary) as 平均工資,department_id from employees where email like '%a%' group by department_id; |
1
2
3
4
5
6
|
#查詢部門員工數量大于2的部門的員工數量(分組后的篩選) #使用 having select count (*) as 員工數量,department_id from employees group by department_id having count (*)>2; |
1
2
3
4
|
#按照多字段 select count (*) as 員工數量,job_id,department_id from employees group by job_id,department_id; |
1
2
3
4
5
6
7
|
#完整結構 select avg (salary) as 平均工資,department_id from employees where department_id is not null group by department_id having avg (salary)>9000 order by avg (salary) desc ; |
到此這篇關于mysql必備基礎之分組函數 聚合函數 分組查詢詳解的文章就介紹到這了,更多相關mysql 分組函數 內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/m0_46653805/article/details/120731863