Home [SQL筆記] Group By、Having 分組查詢
Post
Cancel

[SQL筆記] Group By、Having 分組查詢

R

  • union合併
  • group by 欄位名分組
  • having分組查詢後,要使用「聚合函數」條件,要放在having後面
  • having 子句通常是在一個SQL 句子的最面
  • where不能包含「聚合函數」條件。也就是說where後面不能有「聚合函數」條件。

語法:

1
2
3
4
SELECT "欄位1", SUM("欄位2") 
FROM "表格名" 
GROUP BY "欄位1" 
HAVING (聚合函數條件);

如果 SELECT 的只有函數欄, 那就不需要 GROUP BY 子句。

SQL Having

範例1:根據地區分組,統計員工人數、工資總和、平均工資、最高工資和最低工資

根據員工所在地區分組,統計員工人數、工資總和、平均工資、最高工資和最低工資

  • 方案一:使用union,代碼比較多,不是很好的方法
  • 方案二:使用group by分組。group by 欄位名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
--統計員工人數、工資總和、平均工資、最高工資和最低工資
select count(*) 人數, sum(EmployeeSalary) 工資總和, avg(EmployeeSalary) 平均工資, max(EmployeeSalary) 最高工資, min(EmployeeSalary) 最高工資
from Employee

--根據地區分組(根據員工所在地區分組)
--方案一:使用union (代碼多,不是很好的方案)
select '上海' 地區, count(*) 人數, sum(EmployeeSalary) 工資總和, avg(EmployeeSalary) 平均工資, max(EmployeeSalary) 最高工資, min(EmployeeSalary) 最高工資
from Employee
where EmployeeAddress='上海'
union
select '台北' 地區, count(*) 人數, sum(EmployeeSalary) 工資總和, avg(EmployeeSalary) 平均工資, max(EmployeeSalary) 最高工資, min(EmployeeSalary) 最高工資
from Employee
where EmployeeAddress='台北'

--方案二:使用group by分組
select EmployeeAddress 地區, count(*) 人數, sum(EmployeeSalary) 工資總和, avg(EmployeeSalary) 平均工資, max(EmployeeSalary) 最高工資, min(EmployeeSalary) 最高工資
from Employee
group by EmployeeAddress

範例2:根據地區分組,1985年及以後出生的不統計。統計員工人數、工資總和、平均工資、最高工資和最低工資

使用 group by

1
2
3
4
5
6
--根據地區分組,1985年後不統計。統計員工人數、工資總和、平均工資、最高工資和最低工資
select EmployeeAddress 地區, count(*) 人數, sum(EmployeeSalary) 工資總和, avg(EmployeeSalary) 平均工資, max(EmployeeSalary) 最高工資, min(EmployeeSalary) 最高工資
from Employee
where EmployeeBirth < '1985-1-1'
--where year(EmployeeBirth)< 1985
group by EmployeeAddress

範例3:根據地區分組,1985年及以後出生的不統計,統計員工人數、工資總和、平均工資、最高工資和最低工資,要求篩選員工人數至少2人以上的記錄

使用 having

1
2
3
4
5
6
select EmployeeAddress 地區, count(*) 人數, sum(EmployeeSalary) 工資總和, avg(EmployeeSalary) 平均工資, max(EmployeeSalary) 最高工資, min(EmployeeSalary) 最高工資
from Employee
where EmployeeBirth < '1985-1-1'
--where year(EmployeeBirth)< 1985
group by EmployeeAddress
having count(*) >= 2

https://www.bilibili.com/video/BV1XV411C7TP?p=11

This post is licensed under CC BY 4.0 by the author.