我正在尝试使用余额,结果和收入返回帐户列表
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.BANK_NAME, a.LOCALE, a.[STATUS]
更新
根据以下评论更正了t2左连接语法。
我期待的输出有望从问题中显而易见。对于6个帐户,SQL应返回6个帐户及其帐户的余额,收入和结果。
我提供的SQL问题是数字错误!根据评论,我认为问题源于连接多次,这是错误地汇总金额。
答案 0 :(得分:18)
由于你没有告诉我们what's going wrong(也就是说,除了描述你期望的行为之外你描述的行为),很难说在哪里,但有几种可能性。尼尔指出一个。另一个原因是,由于您在事务表上加入了三次,因此您将事务与事务配对并重复进行。相反,请一次加入事务表,并更改Amount
列的总结。
Select
a.ACCOUNT_ID,
a.BANK_NAME,
a.LOCALE,
a.STATUS,
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.BANK_NAME, a.LOCALE, a.[STATUS]
您可以使用CASE
表达式作为乘法的更具可读性的替代方法:
Select
a.ACCOUNT_ID,
a.BANK_NAME,
a.LOCALE,
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.BANK_NAME, a.LOCALE, a.[STATUS]
答案 1 :(得分:6)
你的意思是:
select
a.ACCOUNT_ID,
a.BANK_NAME,
a.LOCALE,
a.STATUS,
sum(t1.AMOUNT) as BALANCE,
sum(CASE WHEN t2.AMOUNT < 0 THEN t2.Amount ELSE 0 END) as OUTCOME,
sum(CASE WHEN t3.AMOUNT > 0 THEN t3.Amount ELSE 0 END) 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
left join TRANSACTION t3 on t3.ACCOUNT_ID = a.ACCOUNT_ID
group by
a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]
答案 2 :(得分:3)
我不确定为什么你需要多个连接。你不能简单地做一些事情:
Select
a.ACCOUNT_ID
, a.BANK_NAME
, a.LOCALE
, a.STATUS
, Sum ( t.Amount ) As Balance
, Sum( Case When t.Amount < 0 Then Amount End ) As Outcome
, Sum( Case When t.Amount > 0 Then Amount End ) As Income
From ACCOUNT a
Left Join TRANSACTION t
On t.ACCOUNT_ID = a.ACCOUNT_ID
Group By a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]
答案 3 :(得分:1)
TRANSACTION t2的加入应该是 on t2 ,如on t2.ACCOUNT_ID = a.ACCOUNT_ID