2017-09-05 98 views
-1

我有3個表:1.Parent,2.Child1Table和3.Child2Table如何使記錄的聯接不存在於另一個表上?

家長

ParentItem soldQty 
---------------------- 
111   5 
222   10 
333   4 

Child1Table

ParentItem ChildItemID1 soldQty 
------------------------------------- 
555   551    5 
222   221    10 
333   331    14 

Child2Table

ParentItem ChildItemID2 soldQty 
------------------------------------- 
555   552    5 
666   662    10 
333   332    20 

期待輸出

ParentItem QtySold 
--------------------- 
111    5 //5 
222    20 //10 + 10 
333    38 //4 + 14 + 20 
555    10 //5 + 5 
666    10 //10 

是否有可能使用FULL OUTER JOIN實現這一目標?

+0

爲什麼你有兩個不同的子表? – jarlh

+0

@jarlh其實我有3個子表。這是我的情況。 –

+0

你寫了什麼查詢以獲得預期輸出? –

回答

1

UNION ALL您的表格在派生表中。 GROUP BY它的結果:

select ParentItem, sum(soldQty) as QtySold 
from 
(
    select ParentItem, soldQty from Parent 
    union all 
    select ParentItem, soldQty from Child1Table 
    union all 
    select ParentItem, soldQty from Child2Table 
) dt 
group by ParentItem 
0

有在人ParentItem的表,簡單地聯合的數據集,然後聚合。

select parentitem, sum(soldqty) as qtysold 
from 
(
    select parentitem, soldqty from parent 
    union all 
    select parentitem, soldqty from child1table 
    union all 
    select parentitem, soldqty from child2table 
) alldata 
group by parentitem; 
1

您可以使用CTE,如:

DECLARE @Parent TABLE (ParentItem INT, soldQty INT); 
DECLARE @Child1 TABLE (ParentItem INT, ChildItemID1 INT, soldQty INT); 
DECLARE @Child2 TABLE (ParentItem INT, ChildItemID2 INT, soldQty INT); 
/**/ 
INSERT INTO @Parent VALUES 
(111, 5), 
(222, 10), 
(333, 4); 
INSERT INTO @Child1 VALUES 
(555,   551,    5), 
(222,   221,    10), 
(333,   331,    14); 

INSERT INTO @Child2 VALUES 
(555,   552,    5), 
(666,   662,    10), 
(333,   332,    20); 

/**/ 
;With CTE AS (
    SELECT ParentItem, soldQty FROM @Parent 
    UNION ALL 
    SELECT ParentItem, soldQty FROM @Child1 
    UNION ALL 
    SELECT ParentItem, soldQty FROM @Child2 
    ) 
SELECT ParentItem, sum(soldQty) SoldQty 
FROM CTE 
GROUP BY ParentItem; 

Demo

相關問題