In order to get the final result, you can use the PIVOT function but first I would unpivot your col1
and col2
columns so you won't have multiple columns to pivot.
If you have a limited number of columns, then you can hard-code the query:
select REFID, col, [1], [2], [3]
from
(
select REFID, Sequence, col, value
from yourtable
cross apply
(
select 'COL1', col1 union all
select 'COL2', col2
) c (col, value)
) d
pivot
(
max(value)
for sequence in ([1], [2], [3])
) piv
order by refid;
But it you have an unknown number of sequence
values, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(sequence)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT refid, col,' + @cols + '
from
(
select REFID, Sequence, col, value
from yourtable
cross apply
(
select ''COL1'', col1 union all
select ''COL2'', col2
) c (col, value)
) x
pivot
(
max(value)
for Sequence in (' + @cols + ')
) p
order by refid'
execute sp_executesql @query;