這是我模擬了數據: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
任何幫助和建議深表感謝。
我在SQL有點生疏,但嘗試在結尾添加'GROUP BY g.subgroup'。 –