【发布时间】:2018-06-05 09:08:10
【问题描述】:
我有 3 张桌子,如下所示。我想找到平衡
Table A
studentID Name
1 Bob
2 Sam
3 Sara
Table B
id studentID Credit
1 1 100
2 1 150
3 2 150
4 2 150
5 3 100
6 3 200
Table C
id studentID Amount Type
1 1 50 cash
2 1 120 card
3 2 100 cash
4 2 130 card
5 3 50 card
6 3 150 card
我想得到如下结果表,其中 Balance = Sum(credit) - sum(amount) where type = card。
结果表
studentID Name Credit Amount Balance
1 Bob 250 120 130
2 Sam 300 130 170
3 Sara 300 200 100
编辑
根据他的评论,这是他尝试过的查询
select A.studentID,
A.Name,
ISNULL(SUM(B.Credit),0) as [Credit],
ISNULL(SUM(C.Amount),0) as [Amount],
ISNULL(SUM(B.Credit),0) - (select ISNULL(SUM(C.Amount),0) from C Group by C.studentID having C.Type='card' and C.studentID=A.studentID) as [balance]
from A
left outer join B on A.studentID = B.studentID
left outer join C on B.studentID = C.studentID
group by A.studentID
【问题讨论】:
-
我不明白你用来达到预期输出的数学。但除此之外,你有没有尝试过?
-
type列的作用是什么? -
这是我尝试过的。但它不起作用选择 A.studentID,A.Name,ISNULL(SUM(B.Credit),0) 作为 [Credit],ISNULL(SUM(C.Amount),0) 作为 [Amount],ISNULL( SUM(B.Credit),0) - (select ISNULL(SUM(C.Amount),0) from C Group by C.studentID with C.Type='card' and C.studentID=A.studentID) as [balance ] from A left outer join B on A.studentID = B.studentID left outer join C on B.studentID = C.studentID group by A.studentID
-
类型为支付方式。如果他用现金支付,则不应从信用中扣除
-
请将您尝试过的查询添加到您的问题中,而不仅仅是将其作为评论放在此处。我现在已经为您完成了,但请在将来这样做
标签: sql-server group-by aggregate-functions