将一对多的关系分组

时间:2014-04-14 01:56:29

标签: sql join pivot

tableOne

id  name
--  ----
1   A
2   B
3   C

tableTwo

stuffno  id  stuff  stufftype
-------  --  -----  ---------
1        1   D1     D
2        1   E1     E
3        1   F1     F
4        2   D2     D
5        2   E2     E
6        2   F2     F
7        3   D3     D
8        3   E3     E
9        3   F3     F

请求结果:

name  stuffD  stuffE  stuffF
----  ------  ------  ------
A     D1      E1      F1
B     D2      E2      F2
C     D3      E3      F3

如何在一个SQL查询中执行此操作?

3 个答案:

答案 0 :(得分:1)

您可以使用多个JOINtableTwo来获得所需的结果:

SELECT
    p.name as name,
    f.stuff AS stuffF,
    d.stuff AS stuffD,
    e.stuff AS stuffE
FROM
    tableOne p JOIN tableTwo f on (p.id = f.id AND f.stufftype = 'F')
               JOIN tableTwo d on (p.id = d.id AND d.stufftype = 'D')
               JOIN tableTwo e on (p.id = e.id AND e.stufftype = 'E')    

答案 1 :(得分:0)

尝试类似

的内容
SELECT
       t1.name,
       t2.stuff as stuffD,
       t3.stuff as stuffE,
       t4.stuff as stuffF
FROM
       tableOne t1
JOIN
       tableTwo t2
ON
       (t1.id = t2.id
        AND
        t2.stufftype = 'D')
...
and repeat JOIN .. ON ..  for 'E' (tableTwo t3) and 'F' (tableTwo t4)

答案 2 :(得分:0)

尝试下面的sql:

数据: 表@ temp1

ID     Name
------ ------
1      A
2      B
3      C

表@ temp2

No  ID      suffx   sutype
--- ---     -----   ------
1   1   D1  D
2   1   E1  E
3   1   F1  F
4   2   D2  D
5   2   E2  E
6   2   F2  F

SQL

select
    b.stuffNo,a.id,a.name
    ,b.stuffx as 'StuffD'--,b.stufftype
    ,c.stuffx as 'StuffE'--,c.stufftype
    ,d.stuffx as 'StuffF'--,d.stufftype
from
    @temp2 b 
    left join @temp1 a on b.id = a.id and b.stufftype= 'D'
    left join @temp2 c on c.id = a.id and c.stufftype='E'
    left join @temp2 d on d.id = a.id and d.stufftype='F'
where a.id is not null

结果

stuffNo     id          name  StuffD StuffE StuffF
----------- ----------- ----- ------ ------ ------
1           1           A     D1     E1     F1
4           2           B     D2     E2     F2