iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0

聚合函數

聚合函數就是將資料分組後, 進行運算得出統計結果, 用於取大值、取小值、取平均值、取資料筆數、總數、變異數、50百分位數等等。
【注意】使用聚合函數計算統計結果前, 要確認資料型別是數字, 若為字串可能誤判(9>12, MAX=9)

常用的聚合函數

保留字 Function
MAX 取分組資料中最大值
MIN 取分組資料中最小值
SUM 取分組資料中加總結果
AVG 取分組資料中平均值
count 資料總比數
-- 1. 根據數學成績檔案, 取得所有學生的:數學平均、最大、最小、全班總分、學生數
with Math_Score as (
    select 'Amy' name, 67 score
    union all
    select 'Oleve' name, 77 score
    union all
    select 'Jake' name, 78 score
    union all
    select 'James' name, 87 score
    union all
    select 'Black' name, 59 score
)
select AVG(score), MAX(score),MIN(score), SUM(score), count(1) 
from Math_Score
;
-- output
AVG(SCORE) MAX(SCORE) MIN(SCORE) SUM(SCORE)   COUNT(1)
73.6	   87	      59	      368	     5

-- 2. 根據年紀, 取得`同齡`學生的:數學平均、最大、最小、全班總分、學生數
with Math_Score as (
    select 'Amy' name, 15 year, 67 score
    union all
    select 'Oleve' name, 15 year , 77 score
    union all
    select 'Jake' name, 15 year, 78 score
    union all
    select 'James' name, 16 year, 87 score
    union all
    select 'Black' name, 16 year, 59 score
)
select year, AVG(score), MAX(score),MIN(score), SUM(score), count(1) 
from Math_Score
where 1=1
group by year
;
-- output
YEAR   AVG(SCORE)   MAX(SCORE)   MIN(SCORE)   SUM(SCORE)   COUNT(1)
   15	   74	       78	      67	         222   		3
   16	   73	       87    	  59	         146	    2

有條件的分組結果

類似一般查詢的 where 條件語法, 對於分組後的結果想要再進行資料過濾, 可以使用 having 函數來完成。

-- 3. 根據年紀, 取得該年紀有人數學成績大於80分的年齡層數學平均、最大、最小、全班總分、學生數
with Math_Score as (
    select 'Amy' name, 15 year, 67 score
    union all
    select 'Oleve' name, 15 year , 77 score
    union all
    select 'Jake' name, 15 year, 78 score
    union all
    select 'James' name, 16 year, 87 score
    union all
    select 'Black' name, 16 year, 59 score
)
select year, AVG(score), MAX(score),MIN(score), SUM(score), count(1) 
from Math_Score
where 1=1
group by year
having MAX(score) >= 80
;
-- output
YEAR   AVG(SCORE)   MAX(SCORE)   MIN(SCORE)     SUM(SCORE)  	 COUNT(1)
16	   73	        87	          59	        146		          2

Reference


上一篇
Day 9 基礎-把好朋友JOIN在一起
下一篇
Day 11 基礎-資料排序(1)
系列文
不居功的系統隱士 - 30天由淺入深學SQL14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言