“column XYZ must be in group by” --> “cannot group by aggregate column”

谁说胖子不能爱 提交于 2020-01-06 15:17:36

问题


i have trouble with following sql-statement (trimmed):

SELECT nr,
    (CASE WHEN 
        SUM(vkdtab.amount*liter)<>0 AND 
        jjjjmm BETWEEN 201001 and 201009 
    THEN SUM(net)/SUM(vkdtab.amount*liter) 
    ELSE 0 END) as return
FROM tab
GROUP BY 1,2,3

It should give me the amount/liter of items in a special timeframe, but I get the error: column return must be in group by

After I add that column: cannot group by aggregate column.

This is functional, just without the timeframe:

CASE WHEN 
    SUM(vkdtab.amount*liter)<>0
THEN SUM(net)/SUM(vkdtab.amount*liter) 
ELSE 0 END

How can I add the timeframe without getting an error?


回答1:


I'd try changing the GROUP BY to GROUP BY nr, jjjjmm so it matches your unaggregated columns in the SELECT clause. You either GROUP BY or SUM/MIN/COUNT etc

If this is wrong, then the aggregate is wrong because it would fail the "express your aggregate in plain english" test

GROUP BY ordinal is a vile concept too and should be shot.




回答2:


My previous answer was incorrect - you cannot use HAVING in this scenario

You just need to put in the where clause:

SELECT nr,
    (CASE WHEN 
        SUM(vkdtab.amount*liter)<>0 AND 
        jjjjmm BETWEEN 201001 and 201009 
    THEN SUM(net)/SUM(vkdtab.amount*liter) 
    ELSE 0 END) as return
FROM tab

Where jjjjmm BETWEEN 201001 and 201009
And jjjjmm BETWEEN 201013 and 201020

GROUP BY CASE WHEN 
    SUM(vkdtab.amount*liter)<>0
THEN SUM(net)/SUM(vkdtab.amount*liter) 
ELSE 0 END


来源:https://stackoverflow.com/questions/3676569/column-xyz-must-be-in-group-by-cannot-group-by-aggregate-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!