employee 表
id | name | gender | hire_date | salary | performance | manage | deparmant |
---|---|---|---|---|---|---|---|
1001 | 張三 | 男 | 2/12/1991 00:00:00 | 2000 | 200 | 500 | 營銷部 |
1002 | 李四 | 男 | 5/8/1993 00:00:00 | 4000 | 500 | 營銷部 | |
1003 | 王五 | 女 | 12/13/1993 00:00:00 | 1000 | 100 | 5000 | 研發部 |
1004 | 趙六 | 男 | 8/19/1996 00:00:00 | 8000 | 1000 | 4000 | 財務部 |
1005 | 孫七 | 女 | 11/6/1997 00:00:00 | 5000 | 500 | 研發部 | |
1006 | 周八 | 男 | 10/16/1994 00:00:00 | 6000 | 2000 | 1000 | 人事部 |
1007 | 吳九 | 女 | 9/22/1995 00:00:00 | 8000 | 1500 | 研發部 | |
1008 | 鄭十 | 女 | 10/25/1998 00:00:00 | 4000 | 900 | 人事部 |
1.SQL分組查詢GroupBy+Group_concat
group by 是分組,是分組,是分組,分組並不是去重,而是分組
將查詢結果按一個或多個進行分組,字段值相同的為一組
GroupBy+Group_concat : 表示分組之后,根據分組結果,使用 group_contact() 來放置每一組的每字段的值的集合
select deparmant, GROUP_CONCAT(`name`) from employee GROUP BY deparmant
根據 department 分組,通過 group_concat('name'),查看每組里面的姓名都有哪些
SELECT gender,GROUP_CONCAT(`name`) from employee GROUP BY gender
根據gender 分類,看 不同的 性別都有哪些 人
分組注意事項: 在分組時,select后面跟的的字段一般都會出現在 group by 后
SELECT name,gender from employee GROUP BY gender,name
-- 先按gender分組,再按姓名分組...
2.SQL分組+聚合函數
select deparmant, GROUP_CONCAT(salary), SUM(salary),AVG(salary) 平均工資,MAX(salary) 最高工資 from employee GROUP BY deparmant;
-- 根據department 分組,計算各部門下工資總數,平均工資,最高工資
-- 查詢每個部門的部門名稱以及每個部門的人數
SELECT deparmant, GROUP_CONCAT(`name`), COUNT(*) from employee GROUP BY deparmant
-- 查詢每個部門的部門名稱以及每個部門工資大於1500的人數
SELECT deparmant,GROUP_CONCAT(salary), COUNT(*) from employee WHERE salary > 1500 GROUP BY deparmant
3.SQL分組GroupBy+Having
- group by + having 用來分組查詢后指定一些條件來輸出查詢結果
- having 和 where 一樣,但 having 只能用於 group by
-- 查詢工資總和大於 9000的部門名稱
SELECT deparmant, GROUP_CONCAT(salary), SUM(salary) FROM employee
GROUP BY deparmant
HAVING SUM(salary) > 9000;
having 和 where 的區別:
- having 是在分組后對數據進行過濾,where 是在分組前對數據進行過濾
- having后面可以使用分組函數(統計函數),where后面不可以使用分組函數
- where 是對分組前記錄的條件,如果某行記錄沒有滿足where字句的條件,那么這行記錄不會參加分組;而having是對分組后數據的約束
-- 查詢工資大於2000的,工資總和大於9000的部門名稱以及工資和
select deparmant,GROUP_CONCAT(salary), SUM(salary) from employee
WHERE salary > 2000
GROUP BY deparmant
HAVING sum(salary) > 9000
ORDER BY SUM(salary) DESC;