首页 > 解决方案 > sum() 返回多行

问题描述

我试图得到所有负值的总和、所有正值的总和以及总和。这是我的查询:

SELECT
        gl.rowno,
        gl.br
        gl.fs
        gl.cudic
        gl.name
        gl.no_
        gl.balance
        SUM(glhi.amount) AS Total,
        CASE WHEN glhi.amount >0 THEN ISNULL(SUM(glhi.amount),0) END AS TotalPositive,
        CASE WHEN glhi.amount <0 THEN ISNULL(SUM(glhi.amount),0) END AS TotalNegative
FROM gl
        INNER JOIN glhi ON gl.rowno = glhi.rowno
WHERE 
        status = 'active'
        AND glhi.amount != 0.00
        AND glhi.effective BETWEEN '09-01-2017' AND '09-30-2017'
GROUP BY gl.rowno, gl.name, gl.no_, gl.branch, gl.fs, gl.cudic, gl.balance, glhi.effective, glhi.amount
ORDER BY gl.br, gl.name

这是我得到的当前输出的一个例子:

在此处输入图像描述

编辑:显而易见的答案是从我的 GROUP BY 子句中删除 glhi.amount ,但是当我这样做时,我得到了这个错误:

Column 'glhi.amount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

标签: sqlsql-server-2012

解决方案


似乎是正确的结果,当您使用 , 等聚合函数时sumavgcount必须对值进行分组以进行正确的聚合

在您的情况下,您将按此条件对结果进行分组 GROUP BY gl.rowno, gl.name, gl.no_, gl.branch, gl.fs, gl.cudic, gl.balance, glhi.effective, glhi.amount

并且您的字段glhi.amount在表中具有不同的值,因此此查询将为您提供多条记录

此外,请注意,在这种情况下,您应该将总和放在sum函数中

CASE WHEN glhi.amount >0 THEN ISNULL(SUM(glhi.amount),0) END AS TotalPositive,
CASE WHEN glhi.amount <0 THEN ISNULL(SUM(glhi.amount),0) END AS TotalNegative

改成

sum(case when glhi.amount > 0 then coalesce(glhi.amount, 0)) end as TotalPositive
sum(case when glhi.amount < 0 then coalesce(glhi.amount, 0)) end as TotalNegative

推荐阅读