2014-02-11 75 views
0

假設我有3個表我想加入兩列3個表和彙總記錄從這些表2,同時避免記錄重複

答:

--------------- 
    id | name 
--------------- 
    1 | A 
--------------- 
    2 | B 
--------------- 

B:

----------------------- 
    id | val | A_id 
----------------------- 
    1 | 10 | 1 
----------------------- 
    2 | 20 | 2 
----------------------- 
    3 | 30 | 2 
----------------------- 

C:

----------------------- 
    id | val | B_id 
----------------------- 
    1 | 40 | 2 
----------------------- 
    2 | 50 | 2 
----------------------- 
    3 | 60 | 2 
----------------------- 

How我得到這樣的結果:

---------------------------- 
    A_name | B_val | C_val 
---------------------------- 
    A | 10 | 0 
---------------------------- 
    B | 50 | 150 
---------------------------- 

我試着這樣做:

SELECT A.name, SUM(COALESCE(B.val,0)), SUM(COALESCE(C.val,0)) 
FROM A 
LEFT JOIN B ON A.id = B.A_id 
LEFT JOIN C ON B.id = C.B_id 
GROUP BY A 

但它返回此相反:

---------------------------- 
    A_name | B_val | C_val 
---------------------------- 
    A | 10 | 0 
---------------------------- 
    B | 90 | 150 
---------------------------- 

我想這是因爲C有3所記載,與B有關,所以B的第二個記錄乘以3。什麼是獲得我想要的結果的最佳方式?

回答

0

移動計算到子查詢:

select tablea.id, tablea.name, B.B_val, C.C_val FROM tablea 
LEFT JOIN 
(select tablea.id AS id, SUM(COALESCE(tableb.val,0)) as B_val 
from tablea left join tableb on tablea.id = tableb.A_id 
group by tablea.id) AS B ON tablea.id = B.id 
LEFT JOIN 
(select tablea.id AS id, SUM(COALESCE(tablec.valc,0)) as C_val 
from tablea left join tableb on tablea.id = tableb.A_id 
left join tablec on tablec.B_id = tableb.id 
group by tablea.id) AS C on tablea.id = C.id 

http://sqlfiddle.com/#!2/4c268/14

編輯,我曾SQL小提琴設置爲MySQL。代碼沒有任何變化,但這裏的postgres http://sqlfiddle.com/#!15/4c268/1

0

一分爲二的查詢,然後使用這些子查詢作爲數據源的第三個:

-- The first query (it returns the sum of b.val) 
select a.id, a.name, sum(b.val) as sum_b_val 
from a left join b on a.id = b.a_id 
group by a.id; 

-- The second query (it returns the sum of c.val) 
select b.a_id, sum(c.val) as sum_c_val 
from b left join c on b.id = c.b_id 
group by b.a_id; 

-- Put it all together 
select 
    q1.name, 
    coalesce(q1.sum_b_val, 0) as sum_b_val, 
    coalesce(q2.sum_c_val, 0) as sum_c_val 
from 
    (
    select a.id, a.name, sum(b.val) as sum_b_val 
    from a left join b on a.id = b.a_id 
    group by a.id 
) as q1 
    left join (
    select b.a_id, sum(c.val) as sum_c_val 
    from b left join c on b.id = c.b_id 
    group by b.a_id 
) as q2 on q1.id = q2.a_id; 

檢查this example on SQL Fiddle

希望這有助於

0

下面的查詢將只在表A中的id是唯一的時才起作用。

select t1.name,t1.bval,t2.cval from 
(select A.id, A.name, SUM(ISNULL(B.val,0)) bval 
    from A 
    left join b on a.id = b.A_id 
    group by A.id, A.name) t1 
left join 
(select B.A_Id, sum(ISNULL(c.val,0)) cval 
    from B 
    left join c on b.id = c.b_id 
    group by A_ID) t2 
on t1.id = t2.A_Id;