在加入多个表时我真的需要帮助

时间:2015-12-06 09:00:40

标签: sql join

我有3张桌子..

表A

    id     name    amount
---------------------------
    1      xxx     1000.00
    2      yyy      500.00

tableB的

    idkey   project   alloted    
--------------------------------------
    1        xxx       500.00
    1        xxx       500.00 
    2       yyy1       250.00
    2       yyy2       250.00 

表C

   idkey  Proj   item      cost
 -----------------------------
    1      xxx   hammer    500.00
    1      xxx   nail      200.00
    1      xxx   labor     200.00
    2     yyy1   chair     150.00
    2     yyy1   table     100.00
    2     yyy2   chain     100.00
    2     yyy2   spring     50.00

,输出就像这样

    idkey   name   tot_allo  tot_cost
    1        xxx    1000.00    900.00
    2        yyy     500.00    400.00

以及我已经拥有的......

SELECT   tableA.name, SUM(tableB.alloted) as tot_allo,
         SUM(tableC.cost) as  tot_cost 
FROM     tableA LEFT JOIN tableB ON tableA.idkey = tableB.idkey 
            LEFT JOIN tableC ON tableB.idkey = tableC.idkey 
GROUP BY tableA.name

并且这个输出不是我所期待的... tot_allo和tot_cost它使自己的数量加倍......为什么?

table.A.name,    tot_allo,    tot_cost
--------------------------------------
 xxx              2000.00      1800.00
 yyy              1000.00       400.00

我会很高兴有任何帮助:)

1 个答案:

答案 0 :(得分:1)

在加入之前,您需要使用子查询来获取聚合:

select          A.idkey,
                A.name,
                B.tot_allo,
                C.tot_cost
from            tableA A
left outer join (
    select      idkey, sum(alloted) as tot_allo
    from        tableB
    group by    idkey
) B on          B.idkey = A.idkey
left outer join (
    select      idkey, sum(cost) as tot_cost
    from        tableC
    group by    idkey
) C on          C.idkey = A.idkey

使用观点:

create view v_tableB_totals
as
    select      idkey, sum(alloted) as tot_allo
    from        tableB
    group by    idkey

create view v_tableC_totals
as
    select      idkey, sum(cost) as tot_cost
    from        tableC
    group by    idkey

select          A.idkey,
                A.name,
                B.tot_allo,
                C.tot_cost
from            tableA A
left outer join v_tableB_totals B 
    on          B.idkey = A.idkey
left outer join v_tableC_totals C
    on          C.idkey = A.idkey