加入同一个表的SQL JOIN问题

时间:2011-08-21 19:48:01

标签: sql join db2

这是我的模拟数据:

组:

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

我正在尝试编写一个查询,每个SUBGROUP将返回一行,每个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

非常感谢任何帮助和建议。

1 个答案:

答案 0 :(得分: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');