sql - 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.
解决方案
似乎是正确的结果,当您使用 , 等聚合函数时sum
。avg
您count
必须对值进行分组以进行正确的聚合
在您的情况下,您将按此条件对结果进行分组
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
推荐阅读
- tibco-ems - 如何在 TIBCO EMS 上创建专用 DLQ?
- python - Python Selenium 不写'@'。而是用其他代码填充
- python - AttributeError:“NoneType”对象没有属性“复制”错误
- microsoft-graph-api - 调用/beta/informationprotection/policy/labels时得到404“找不到资源”
- kong - 不同路线中的相似路径变得不匹配
- go - 错误在戈兰下划线没有解释
- javascript - R string replacing part of javascript
- php - Laravel 验证规则有时 + required_without
- python - 如何替换数据框列中的所有数字(附有字母/符号,即 43$)?
- python - xlsxwriter 循环