Here is my mock up data:
Groups:
MAINGROUP SUBGROUP
1 A
2 A
3 A
1 B
2 B
3 C
1 D
2 D
3 D
2 E
3 E
I'm trying to write a query that will return me one row per SUBGROUP, with one field for each MAINGROUP displaying the group number. If the subgroup does not have a matching group, I want that group field to be NULL.
Here's what I want:
Subgroup G1 G2 G3
A 1 2 3
B 1 2
C 3
Here's my query:
SELECT
g.subgroup AS Subgroup,
1.maingroup AS G1,
2.maingroup AS G2, 开发者_如何学C
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')
And here's what I'm getting:
Subgroup G1 G2 G3
A 1
A 2
A 3
B 1
B 2
B
C
C
C 3
Any help and advice much appreciated.
Try this:
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');
精彩评论