1. 程式人生 > 其它 >SQL|group by 函式使用

SQL|group by 函式使用

技術標籤:簡單避坑sql資料庫資料分析

1.作用
針對原資料做分組處理,一般會與sum()、max()等聚合函式一起使用

2.使用方法
原資料:
在這裡插入圖片描述
求每個學生的總成績

select studentID,sum(score) 
from score_table
group by studentID

3.注意事項
在使用group by時,select之後的欄位要麼包含在聚合函式裡,要麼在group by 之後
eg:分不同課程取出最高的成績及對應的學生ID

select class, studentID, max(score) 
from score_table
group by class

上述問題就會報錯,因為studengID既不是聚合函式,也不再group by裡。
從實際理解來看,sql會先執行group by語句,再執行select語句,如果只對class 分組不對studentID進行分組,所有學生的成績會在一個分組裡,後臺在執行select 時無法得知studentID的取值限制

注:sql語句執行順序 from - join on - where - group by - having -select - order by