Men hvis du vil have DYNAMISK:Sql DEMO
Først skal du bruge en tidslig tabel for at oprette en række_id
SELECT row_number() over (partition by [Country] order by [StateCity]) [rn],
[StateCity],
[Country]
INTO temp
FROM State;
Så kan du gå den dynamiske pivotrute
Opret de forskellige kolonner
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Country])
FROM temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
Opret pivotforespørgslen:
set @query = 'SELECT rn, ' + @cols + ' from
(
select [rn]
, [StateCity]
, [Country]
from temp
) x
pivot
(
max(StateCity)
for [Country] in (' + @cols + ')
) p ';
Udfør det
execute(@query);
OUTPUT: