must appear in the GROUP BY clause or be used in an aggregate function

今天在分組統計的時候pgsql報錯 must appear in the GROUP BY clause or be used in an aggregate function,在mysql裏面是能夠的,可是pgsql報錯,我去stackoverflow查詢了一下,發現有人遇到過和我同樣的問題,這是pgsql一個常見的聚合問題,在SQL3標準之前,選擇顯示的字段必須出如今在 GROUP BY 中。下面我把問題描述一下:mysql

有一張表叫 makerar,表中記錄以下: cname | wmname | avg
--------|--------|----------------------- canada | zoro | 2.00 spain | luffy | 1.00 spain | usopp | 5.00sql

我想要查詢每一個 cname 的最大 avg,按照mysql的寫法是app

SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;

在pgsql中報錯函數

ERROR:  column "makerar.wmname" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: SELECT cname, wmname, MAX(avg)  FROM makerar GROUP BY cname;

意思是 wmname 字段必須在 GROUP BY 中出現或者被用於聚合函數url

因而我按照錯誤提示,把 wmname 字段加在 GROUP BY 後面,即spa

SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname, wmname;

獲得的結果是.net

cname wmname avg
canada zoro 2.00
spain luffy 1.00
spain usopp 5.00

而我指望獲得的結果是code

cname wmname avg
canada zoro 2.00
spain usopp 5.00

解決方案有兩種,可是我只看懂了一種,因而把這一種記錄一下get

大致思路是在子查詢中完成聚合,而後關聯包含你想顯示字段的表(這裏是makerar自身)獲取字段(這裏是wmname),因此sql就變成了下面這個樣子io

SELECT   
  t.cname,
  m.wmname,
  t.max
FROM 
  (SELECT 
    cname,
    MAX(avg) AS max 
  FROM makerar
  GROUP BY cname) t
LEFT JOIN makerar m ON t.cname = m.cname AND t.max = m.avg;

參考連接

https://stackoverflow.com/questions/19601948/must-appear-in-the-group-by-clause-or-be-used-in-an-aggregate-function#

相關文章
相關標籤/搜索