SQL Server,在单个查询中显示多个表的合计金额

时间:2018-09-27 09:39:59

标签: sql-server

我有这些表,每个表可以有多行。

  • 表ta(eid,金额)
  • 表tb(eid,金额)
  • 表tc(eid,金额)

每个表都有这样的数据行:

ta:

1001  100.00
1001   20.10

待定:

1001   200.00
1001   32.10

tc:

1001   300.00
1001   20.10

我需要的解决方案:具有eid的单行和每个表的“金额”列的汇总

1001   120.10     232.10   320.10

我尝试过此方法,但它显示的是数量乘以我正在使用的表的数量

select 
    ta.eid, 
    sum(ta.Amount) as taAmount, 
    sum(tb.Amount) as tbAmount, 
    sum(tc.Amount) as tcAmount
from 
    ta , tb, tc
where 
    ta.eid = tb.eid 
    and tb.eid = tc.eid
group by 
    ta.eid

请帮助我知道如何实现?

1 个答案:

答案 0 :(得分:2)

利用派生表或CTE首先获取合计金额

select ta.eid, ta.amount, tb.amount, tc.amount
from   (select eid, amount= sum(amount) from ta group by eid) ta
join   (select eid, amount= sum(amount) from tb group by eid) tb on ta.eid = tb.eid
join   (select eid, amount= sum(amount) from tc group by eid) tc on ta.eid = tc.eid

如果eid可能未出现在所有表格中,则可以获取eid列表,然后LEFT JOIN依次显示ta,tb和tc

select i.eid, ta.amount, tb.amount, tc.amount
from   (select eid from ta union select eid from tb union select eid from tc) i
left join (select eid, amount= sum(amount) from ta group by eid) ta on i.eid = ta.eid
left join (select eid, amount= sum(amount) from tb group by eid) tb on i.eid = tb.eid
left join (select eid, amount= sum(amount) from tc group by eid) tc on i.eid = tc.eid