關於Mysql分組聚合函式的乙個大坑(易錯點)

2022-09-16 20:03:14 字數 1271 閱讀 9920

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 **g(`s_score`) desc

輸出正確結果:

但是在想:既然case都判定課程編號了,那為什麼還要用聚合函式max(sum也可以)呢?去掉聚合函式之後。

select `s_id`, **g(`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 **g(`s_score`) desc

輸出結果:

明顯出現錯誤。

分析:這裡跟case when沒有多大關係,這是因為分組函式一定和聚合函式一同存在,要不然你想,比如上述資料,按照名字分組後,每個組內都有三個資料,而展示的時候就只展示第一條,而只有當與聚合函式一起使用的時候才會在聚合列的要選擇字段進行迭代。

同理:sql書寫要求:「出現在select子句中的單獨的列,必須出現在group by子句中作為分組列」

分組聚合函式使用

1.mysql 的分組合併函式group concat group concat 會計算哪些行屬於同一組,將屬於同一組的列顯示出來。要返回哪些列,由函 數引數 就是欄位名 決定。分組必須有個標準,就是根據group by指定的列進行分組。例 select 分組字段,group concat 合併字段...

記錄下mysql的分組聚合函式group by

今天維護客戶的儲存過程時發現乙個問題,連鎖客戶只有銷售明細表,沒訂單表,而公司要求寫查詢訂單的儲存過程,客戶那邊使用的資料是sqlserver,我使用了分組聚合函式group by 例如 這樣子寫sqlserver會報錯,因為group by 要求查詢的字段也得包含在聚合函式裡。select ord...

MySQL常用聚合函式

官方文件 aggregate group by functions name description g return the erage value of the argument bit and return bitwise and bit or return bitwise or bit xo...