由于您使用的是 SQL Server,因此您可以通过多种不同的方式获得结果,但所有这些方式都涉及使用row_number()
.
您可以将聚合函数与 CASE 表达式一起使用:
select visitnumber,
max(case when seq=1 then id end) ID1,
max(case when seq=2 then id end) ID2,
max(case when seq=3 then id end) ID3,
max(case when seq=4 then id end) ID4,
max(case when seq=5 then id end) ID5
from
(
select visitnumber, id,
row_number() over(partition by visitnumber
order by id) seq
from yourtable
) d
group by visitnumber;
请参阅带有演示的 SQL Fiddle
您可以使用 PIVOT 功能:
select visitnumber, ID1, ID2, ID3, ID4, ID5
from
(
select visitnumber, id,
'ID'+cast(row_number() over(partition by visitnumber
order by id) as varchar(10)) seq
from yourtable
) d
pivot
(
max(id)
for seq in (ID1, ID2, ID3, ID4, ID5)
) piv;
请参阅SQL Fiddle with Demo。你说你最多只能有 5 个 id,但如果你有一个未知的数字,那么你可以使用动态 SQL 来获得结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('ID'+cast(row_number() over(partition by visitnumber
order by id) as varchar(10)))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT visitnumber,' + @cols + '
from
(
select visitnumber, id,
''ID''+cast(row_number() over(partition by visitnumber
order by id) as varchar(10)) seq
from yourtable
) x
pivot
(
max(id)
for seq in (' + @cols + ')
) p '
execute sp_executesql @query;
请参阅SQL Fiddle with Demo。所有版本都会给出一个结果:
| VISITNUMBER | ID1 | ID2 | ID3 | ID4 | ID5 |
------------------------------------------------------------
| 39332 | 759666 | 769445 | 775795 | 783781 | 861130 |
| 40329 | 762595 | 769447 | 775796 | 783782 | (null) |