MySQL(七)DQL之分組查詢
一、語法
select 分組函數,分組後的字段from 表【where 篩選條件】group by 分組的字段【having 分組後的篩選】【order by 排序列表】
二、特點
分組前篩選:where - 原始表 - group by的前面
分組後篩選:having - 分組後的結果 - group by 的後面
三、簡單的分組
案例1:查詢每個工種的員工平均工資
SELECT AVG(salary),job_id FROM employees GROUP BY job_id;
案例2:查詢每個位置的部門個數
SELECT COUNT(*),location_id FROM departments GROUP BY location_id;
四、分組前篩選
案例1:查詢郵箱中包含a字符的 每個部門的最高工資
SELECT MAX(salary),department_id FROM employees WHERE email LIKE ‘%a%‘ GROUP BY department_id;
案例2:查詢有獎金的每個領導手下員工的平均工資
SELECT AVG(salary),manager_id FROM employees WHERE commission_pct IS NOT NULL GROUP BY manager_id;
五、分組後篩選
案例1:查詢哪個部門的員工個數>5
SELECT COUNT(*),department_id FROM employees GROUP BY department_id HAVING COUNT(*)>5;
案例2:每個工種有獎金的員工的最高工資>12000的工種編號和最高工資
SELECT job_id,MAX(salary) FROM employees WHERE commission_pct IS NOT NULL GROUP BY job_id HAVING MAX(salary)>12000;
案例3:領導編號>102的每個領導手下的最低工資大於5000的領導編號和最低工資
SELECT manager_id,MIN(salary) FROM employees WHERE manager_id > 102 GROUP BY manager_id HAVING MIN(salary)>5000;
六、添加排序
案例:每個工種有獎金的員工的最高工資>6000的工種編號和最高工資,按最高工資升序
SELECT job_id, MAX(salary) m FROM employees WHERE commission_pct IS NOT NULL GROUP BY job_id HAVING m >6000 ORDER BY m;
七、按多個字段分組
案例:查詢每個工種每個部門的最低工資,並按最低工資降序
SELECT MIN(salary),job_id,department_id FROM employees GROUP BY department_id,job_id ORDER BY MIN(salary) DESC;
關註公眾號:Java後端生活,幹貨文章第一時間送達!
MySQL(七)DQL之分組查詢