小编典典

SQL查询以汇总不同表中的字段

sql

我是一个讨厌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的Id,总计和Amount字段的总和,如下所示

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

编辑:我有一个错字。该查询没有给出正确的结果。扩展了示例。


阅读 177

收藏
2021-03-17

共1个答案

小编典典

或者,您可以利用使用子查询的优势:

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
2021-03-17