如果您想将sequence
数字作为列名的一部分包含在内,那么您仍然需要先取消透视col1
和col2
列,然后再应用透视。不同之处在于您会将sequence
数字连接到在反透视过程中创建的列名。
对于已知数量的值,查询将是:
select REFID,
[1col1], [2col1], [3col1],
[1col2], [2col2], [3col2]
from
(
select REFID,
col = cast(Sequence as varchar(10))+ col, value
from yourtable
cross apply
(
select 'COL1', col1 union all
select 'COL2', col2
) c (col, value)
) d
pivot
(
max(value)
for col in ([1col1], [2col1], [3col1],
[1col2], [2col2], [3col2])
) piv
order by refid;
然后,如果您有一个未知数字,则动态 SQL 版本将是:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(cast(Sequence as varchar(10))+ col)
from yourtable
cross apply
(
select 'Col1', 1 union all
select 'Col2', 2
) c(col, so)
group by Sequence, col, so
order by so, sequence
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT refid, ' + @cols + '
from
(
select REFID,
col = cast(Sequence as varchar(10))+ col, value
from yourtable
cross apply
(
select ''COL1'', col1 union all
select ''COL2'', col2
) c (col, value)
) x
pivot
(
max(value)
for col in (' + @cols + ')
) p
order by refid'
execute sp_executesql @query;