“列XYZ必须分组” - > “无法按聚合列分组”

时间:2010-09-09 12:37:53

标签: sql group-by aggregate sum

我在使用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

它应该在特定时间范围内给我一定数量/升的物品,但我收到错误:column return must be in group by

我添加该列后:cannot group by aggregate column

这是功能性的,没有时间框架:

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

如何在不收到错误的情况下添加时间范围?

2 个答案:

答案 0 :(得分:2)

我尝试将GROUP BY更改为GROUP BY nr, jjjjmm,以便它与SELECT子句中的未聚合列相匹配。您可以是GROUP BY或SUM / MIN / COUNT等

如果这是错误的,那么聚合是错误的,因为它会失败“用普通英语表达你的聚合”测试

GROUP BY ordinal也是一个卑鄙的概念,应该被拍摄。

答案 1 :(得分:0)

我之前的回答不正确 - 您无法在此方案中使用HAVING

你只需要输入where子句:

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