代码之家  ›  专栏  ›  技术社区  ›  Akshay

SQL Server,在单个查询中显示多个表的聚合量

  •  0
  • Akshay  · 技术社区  · 6 年前

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

    • 表ta(eid,金额)

    每个表都有如下数据行:

    1001  100.00
    1001   20.10
    

    结核病:

    1001   200.00
    1001   32.10
    

    技术合作:

    1001   300.00
    1001   20.10
    

    我需要的解决方案是:带有eid的单行和每个表的amount列的聚合

    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 回复  |  直到 6 年前
        1
  •  2
  •   Squirrel    6 年前

    首先利用派生表或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