2011-08-21 75 views
0

這是我模擬了數據:SQL JOIN問題加入同桌

組:

MAINGROUP SUBGROUP 
1   A 
2   A 
3   A 
1   B 
2   B 
3   C 
1   D 
2   D 
3   D 
2   E 
3   E 

我想編寫一個查詢將返回我一個行每個子組,其中一個領域每個MAINGROUP顯示組編號。如果子組沒有匹配的組,我希望該組字段爲NULL。

這是我想要的東西:

Subgroup G1 G2 G3 
A   1 2 3 
B   1 2 
C     3 

這裏是我的查詢:

SELECT 
    g.subgroup AS Subgroup, 
    1.maingroup AS G1, 
    2.maingroup AS G2, 
    3.maingroup AS G3, 
FROM Groups g 
LEFT JOIN(
     SELECT maingroup, subgroup 
     FROM Groups 
     WHERE maingroup = 1 
     ) 1 
     ON g.subgroup=1.subgroup 
     AND g.maingroup=1.maingroup 
LEFT JOIN(
     SELECT maingroup, subgroup 
     FROM Groups 
     WHERE maingroup = 2 
     ) 2 
     ON g.subgroup=2.subgroup 
     AND g.maingroup=2.maingroup 
LEFT JOIN(
     SELECT maingroup, subgroup 
     FROM Groups 
     WHERE maingroup = 3 
     ) 3 
     ON g.subgroup=3.subgroup 
     AND g.maingroup=3.maingroup 
WHERE g.subgroup IN ('A','B','C') 

這裏就是我得到:

Subgroup G1 G2 G3 
A   1  
A    2 
A     3 
B   1  
B    2 
B 
C   
C   
C     3 

任何幫助和建議深表感謝。

+0

我在SQL有點生疏,但嘗試在結尾添加'GROUP BY g.subgroup'。 –

回答

1

試試這個:

SELECT g.subgroup AS Subgroup, 
    mg1.maingroup AS G1, 
    mg2.maingroup AS G2, 
    mg3.maingroup AS G3 
FROM (SELECT DISTINCT subgroup FROM Groups) g 
LEFT JOIN Groups mg1 ON mg1.maingroup = 1 AND mg1.subgroup = g.subgroup 
LEFT JOIN Groups mg2 ON mg2.maingroup = 2 AND mg2.subgroup = g.subgroup 
LEFT JOIN Groups mg3 ON mg3.maingroup = 3 AND mg3.subgroup = g.subgroup 
WHERE g.subgroup IN ('A','B','C'); 
+0

我的第一反應就是試圖採用你的查詢。這一個應該會更好。此外,第一個有一個或兩個錯誤:\ –

+0

非常好,它的工作。感謝道格。那麼工作如何? – Paul

+0

雖然第一個工作正常。這是一個更好的性能?爲什麼會這樣? – Paul