SQL Query用于汇总来自不同表的字段

时间:2010-02-20 09:08:59

标签: sql select join sum

我是一个讨厌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讨厌我)。

编辑:我有一个错字。此查询未提供正确的结果。扩展了这个例子。

5 个答案:

答案 0 :(得分:18)

或者您可以利用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

答案 1 :(得分:2)

根据您的说明,当您在组中使用不存在的列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;

答案 2 :(得分:1)

这个也很好用

BadRequest

答案 3 :(得分:0)

这可能有助于其他用户。

SELECT Total=(Select Sum(Amount) from table a)+(Select Sum(Amount) from table b)+(Select Sum(Amount) from table c)

答案 4 :(得分:-1)

试试这段代码 SELECT Total = isnull((从表a)中选择Sum(Isnull(Amount,0)),0)+ isnull((从表b)中选择Sum(isnull(Amount,0)),0)+ isnull((选择Sum) (isnull(Amount,0))来自表c),0)