關於Mysql分組聚合函式的一個大坑(易錯點)
阿新 • • 發佈:2020-09-08
score 表格如下:
題目:按平均成績從高到低顯示所有學生的所有課程的成績以及平均成績
select `s_id`, avg(`s_score`), max(CASE when `c_id` = 01 then `s_score` else null end) as "語文", max(CASE when `c_id` = 02 then `s_score` else null end) as "數學", max(CASE when `c_id` = 03 then `s_score` else null end) as "英語" FROM score group BY `s_id` ORDER BY avg(`s_score`) desc
輸出正確結果:
但是在想:既然case都判定課程編號了,那為什麼還要用聚合函式max(sum也可以)呢?去掉聚合函式之後。
select `s_id`, avg(`s_score`), (CASE when `c_id` = 01 then `s_score` else null end) as "語文", (CASE when `c_id` = 02 then `s_score` else null end) as "數學", (CASE when `c_id` = 03 then `s_score` else null end) as "英語" FROM score group BY `s_id` ORDER BY avg(`s_score`) desc
輸出結果:
明顯出現錯誤。
分析:這裡跟case when沒有多大關係,這是因為分組函式一定和聚合函式一同存在,要不然你想,比如上述資料,按照名字分組後,每個組內都有三個資料,而展示的時候就只展示第一條,而只有當與聚合函式一起使用的時候才會在聚合列的要選擇欄位進行迭代。
同理:sql書寫要求:“出現在SELECT子句中的單獨的列,必須出現在GROUP BY子句中作為分組列”