2

我有表:

    ID   Note
1   1    aaa
2   1    bbb
3   1    ccc
4   2    ddd
5   2    eee
6   2    fff

我需要将其返回为:

   ID   Note1   Note2   Note3
1  1    aaa     bbb     ccc
2  2    ddd     eee     fff

谢谢!

4

1 回答 1

3

您可以使用该PIVOT函数进行此类查询。如果您有已知数量的列,则可以对这些值进行硬编码:

select *
from
(
  select id, note,
    'Note' + 
       cast(row_number() over(partition by id order by id) as varchar(10)) col
  from yourtable
) x
pivot
(
  max(note)
  for  col in ([Note1], [Note2], [Note3])
) p

请参阅带有演示的 SQL Fiddle

如果您想要将未知数量的notes列转换为列,则可以使用动态 sql:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' 
                      + QUOTENAME('Note' + 
                       cast(row_number() over(partition by id order by id) as varchar(10))) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id,' + @cols + ' from 
             (
               select id, note,
                ''Note'' + 
                   cast(row_number() over(partition by id order by id) as varchar(10)) col
              from yourtable
            ) x
            pivot 
            (
                max(note)
                for col in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

两者都会产生相同的结果。

| ID | NOTE1 | NOTE2 | NOTE3 |
------------------------------
|  1 |   aaa |   bbb |   ccc |
|  2 |   ddd |   eee |   fff |

或者,如果您不想使用该PIVOT函数,则可以使用带有CASE语句的聚合函数:

select id,
  max(case when rn = 1 then note else '' end) Note1,
  max(case when rn = 2 then note else '' end) Note2,
  max(case when rn = 3 then note else '' end) Note3
from
(
  select id, note,
    row_number() over(partition by id order by id) rn
  from yourtable
) src
group by id

请参阅带有演示的 SQL Fiddle

于 2012-11-02T16:38:42.157 回答