2014-02-28 46 views
0

我已經下面的查詢給我什麼,我wan't(見table_entrees)只能加入一個表中的列與另一個表

SELECT designation, ref1, ref2, ref3, sum(a.qte) AS TotalQte 
FROM table_entrees a 
WHERE a.ref1 = 'VT2' 
GROUP BY a.designation, a.ref1, a.ref2, a.ref3 

table_entrees:

designation ref1 ref2 ref3 TotalQte 
VT   VT2  GRIS L  150 
VT   VT2  GRIS XL  150 
VT   VT2  Jaune L  150 
VT   VT2  Jaune XL  150 

和另一個查詢相同的第一個,但對於另一個表

SELECT designation, ref1, ref2, ref3, sum(b.qte) AS TotalQte2 
FROM table_sorties b 
WHERE a.ref1 = 'VT2' 
GROUP BY b.designation, b.ref1, b.ref2, b.ref3 

table_sorties:

designation ref1 ref2  ref3 TotalQte2 
VT   VT2 GRIS  L  62 
VT   VT2 JAUNE  L  15 

但問題是,我已經試過就像下面的表格,它檢查是否REF1,REF2,table_sorties的REF3在table_entrees存在兩者之間的結合,然後顯示出它的結果還顯示TotalQte2 0

designation ref1 ref2 ref3 TotalQte  TotalQte2 
VT   VT2  GRIS L  150   62 
VT   VT2  GRIS XL  150   0 
VT   VT2  Jaune L  150   15 
VT   VT2  Jaune XL  150   0 

我試過以下查詢,但沒有給出預期的結果!

SELECT 
    a.designation, 
    a.ref1, 
    a.ref2, 
    a.ref3, 
    sum(a.qte) AS TotalQte, 
    sum(b.qte) AS TotalQte2 
FROM FROM table_entrees a,table_sorties b 
WHERE a.ref1 = 'VT2' 
GROUP BY a.designation, a.ref1, a.ref2, a.ref3 
+0

你有可以加入表格的ID列或唯一標識符嗎? –

回答

0

使用每個查詢作爲子查詢,並使用left outer join

SELECT q1.designation, q1.ref1, q1.ref2, q1.ref3, q1.TotalQte, 
     coalesce(q2.TotalQte2, 0) as TotalQte2 
FROM (SELECT designation, ref1, ref2, ref3, sum(a.qte) AS TotalQte 
     FROM table_entrees a 
     WHERE a.ref1 = 'VT2' 
     GROUP BY a.designation, a.ref1, a.ref2, a.ref3 
    ) q1 LEFT JOIN 
    (SELECT designation, ref1, ref2, ref3, sum(b.qte) AS TotalQte2 
     FROM table_sorties b 
     WHERE a.ref1 = 'VT2' 
     GROUP BY b.designation, b.ref1, b.ref2, b.ref3 
    ) q2 
    on q1.designation = q2.designation and 
     q1.ref1 = q2.ref1 and 
     q1.ref2 = q2.ref2 and 
     q1.ref3 = q2.ref3; 

當你做對的聚集加盟之前,你從兩個qte領域的所有組合的笛卡爾乘積表。通常,笛卡爾產品上的sum()將不正確。

+0

@ 0x58。 。 。 「加入」條件中存在拼寫錯誤。它應該現在正確工作。 –

+0

ouh好,謝謝你糾正它。 – 0x58

0

基本上你想要在三個ref列上做一個左連接,如前面的答案所述。

當您執行左連接B時,表A中的所有列都將保留。如果表B中沒有相應的條目,則它將顯示爲空。

相關問題