您可以实现该PIVOT
函数来执行这种数据转换。如果您有已知数量的值,则可以对查询进行硬编码:
select *
from
(
select [user], session, response,
'response'+ cast(row_number() over(partition by [user], session order by response) as varchar(10)) rn
from yourtable
) src
pivot
(
max(response)
for rn in ([response1], [response2])
) piv
请参阅带有演示的 SQL Fiddle
但是,如果您有未知数量的响应,那么您将需要使用动态 sql:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('response'+ cast(row_number() over(partition by [user], session order by response) as varchar(10)))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [user], session, ' + @cols + ' from
(
select [user], session, response,
''response''+ cast(row_number() over(partition by [user], session order by response) as varchar(10)) rn
from yourtable
) x
pivot
(
max(response)
for rn in (' + @cols + ')
) p '
execute(@query)
请参阅带有演示的 SQL Fiddle
两者都会产生相同的结果:
| USER | SESSION | RESPONSE1 | RESPONSE2 |
------------------------------------------
| u1 | s1 | r1 | r2 |
| u1 | s2 | r3 | (null) |
| u2 | s2 | r4 | r5 |