SQL Query用于汇总来自不同表的字段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Query用于汇总来自不同表的字段相关的知识,希望对你有一定的参考价值。
我是一个讨厌SQL的谦虚程序员...... :)请帮我解决这个问题。
我有4个表,例如:
Table A:
Id Total
1 100
2 200
3 500
Table B
ExtId Amount
1 10
1 20
1 13
2 12
2 43
3 43
3 22
Table C
ExtId Amount
1 10
1 20
1 13
2 12
2 43
3 43
3 22
Table D
ExtId Amount
1 10
1 20
1 13
2 12
2 43
3 43
3 22
我需要创建一个SELECT,显示表B,C和D的Amount字段的Id,Total和SUM,就像这样
Id Total AmountB AmountC AmountD
1 100 43 43 43
2 200 55 55 55
3 500 65 65 65
我已尝试使用Id对三个表的内部联接并进行金额字段的总和,但结果并不严格。这是错误的查询:
SELECT dbo.A.Id, dbo.A.Total, SUM(dbo.B.Amount) AS Expr1, SUM(dbo.C.Amount) AS Expr2, SUM(dbo.D.Amount) AS Expr3
FROM dbo.A INNER JOIN
dbo.B ON dbo.A.Id = dbo.B.ExtId INNER JOIN
dbo.C ON dbo.A.Id = dbo.C.ExtId INNER JOIN
dbo.D ON dbo.A.Id = dbo.D.ExtId
GROUP BY dbo.A.Id, dbo.A.Total
在此先感谢,它只是我讨厌SQL(或SQL讨厌我)。
编辑:我有一个错字。此查询未提供正确的结果。扩展了这个例子。
或者您可以利用SubQueries:
select A.ID, A.Total, b.SB as AmountB, c.SC as AmountC, d.SD as AmountD
from A
inner join (select ExtID, sum(Amount) as SB from B group by ExtID) b on A.ID = b.ExtID
inner join (select ExtID, sum(Amount) as SC from C group by ExtID) c on c.ExtID = A.ID
inner join (select ExtID, sum(Amount) as SD from D group by ExtID) d on d.ExtID = A.ID
从您的描述中,当您在组中使用不存在的列dbo.A.Amount
时,此查询应该会给您一个错误。将此更改为dbo.A.Total
可能就是您所需要的。
如果您需要所有金额,请尝试以下查询:
select A.Id, A.Total, sum(B.Amount + C.Amount + D.Amount) AS Total_Amount
from A
inner join B on A.Id = B.ExtId
inner join C on A.Id = C.ExtId
inner join D on A.Id = D.ExtId
group by A.Id, A.Total;
这个也很好用
SELECT (SELECT SUM(Amount) FROM TableA) AS AmountA,
(SELECT SUM(Amount) FROM TableB) AS AmountB,
(SELECT SUM(Amount) FROM TableC) AS AmountC,
(SELECT SUM(Amount) FROM TableD) AS AmountD
这可能有助于其他用户。
SELECT Total=(Select Sum(Amount) from table a)+(Select Sum(Amount) from table b)+(Select Sum(Amount) from table c)
尝试此代码SELECT Total = isnull((从表a)中选择Sum(Isnull(Amount,0)),0)+ isnull((从表b)中选择Sum(isnull(Amount,0)),0)+ isnull( (从表c)中选择Sum(isnull(Amount,0)),0)
以上是关于SQL Query用于汇总来自不同表的字段的主要内容,如果未能解决你的问题,请参考以下文章
SQL一次性查询一个字段不同条件下的统计结果(另一张表的统计数量)