sql – 如何在一个GROUP BY的多个条件下的SUM列

前端之家收集整理的这篇文章主要介绍了sql – 如何在一个GROUP BY的多个条件下的SUM列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用余额,结果和收入返回账目清单
Account            Transaction
-------            -----------
AccountID          TransactionID
BankName           AccountID
Locale             Amount
Status

这是我目前拥有的.有人可以解释我在哪里错了吗?

select
    a.ACCOUNT_ID,a.BANK_NAME,a.LOCALE,a.STATUS,sum(t1.AMOUNT) as BALANCE,sum(t2.AMOUNT) as OUTCOME,sum(t3.AMOUNT) as INCOME
from ACCOUNT a
left join TRANSACTION t1 on t1.ACCOUNT_ID = a.ACCOUNT_ID
left join TRANSACTION t2 on t2.ACCOUNT_ID = a.ACCOUNT_ID and t2.AMOUNT < 0
left join TRANSACTION t3 on t3.ACCOUNT_ID = a.ACCOUNT_ID and t3.AMOUNT > 0
group by a.ACCOUNT_ID,a.[STATUS]

UPDATE

根据下面的注释修改了t2左连接语法.

我期望的输出从这个问题是有希望的显而易见的.对于6个帐户,sql应该返回6个帐户,其余额,收入和结果.

我提供的sql的问题是数字是错误的!根据意见,我认为这个问题源于多次加入,这是不正确的总和.

解决方法

既然你没有告诉我们 what’s going wrong(也就是描述除了描述你所期望的行为之外你所得到的行为),很难说出哪里,但有几种可能性.尼尔指出一个.另一个原因是,由于您在交易表中加入了三次,因此您将交易与交易配对并获得重复.而是单次加入事务表,并更改如何总结Amount列.
Select
    a.ACCOUNT_ID,sum(t.AMOUNT) as BALANCE,sum((t.AMOUNT < 0) * t.AMOUNT) As OUTGOING,sum((t.AMOUNT > 0) * t.AMOUNT) As INCOMING
From ACCOUNT a
Left Join TRANSACTION t On t.ACCOUNT_ID = a.ACCOUNT_ID
Group By a.ACCOUNT_ID,a.[STATUS]

您可以使用CASE表达式作为乘法的更可读的替代方法

Select
    a.ACCOUNT_ID,a.[STATUS],sum(t.AMOUNT) As BALANCE,sum(CASE WHEN t.AMOUNT < 0 THEN t.AMOUNT ELSE 0 end) As OUTCOME,sum(CASE WHEN t.AMOUNT > 0 THEN t.AMOUNT ELSE 0 end) As INCOME
From ACCOUNT a
Left Join [TRANSACTION] t On t.ACCOUNT_ID = a.ACCOUNT_ID
Group By a.ACCOUNT_ID,a.[STATUS]
原文链接:https://www.f2er.com/mssql/81422.html

猜你在找的MsSQL相关文章