Tetapi jika Anda ingin DINAMIS:Sql DEMO
Pertama, Anda memerlukan tabel temporal untuk membuat row_id
SELECT row_number() over (partition by [Country] order by [StateCity]) [rn],
[StateCity],
[Country]
INTO temp
FROM State;
Kemudian Anda dapat pergi ke rute pivot dinamis
Buat kolom yang berbeda
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Country])
FROM temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
Buat kueri pivot:
set @query = 'SELECT rn, ' + @cols + ' from
(
select [rn]
, [StateCity]
, [Country]
from temp
) x
pivot
(
max(StateCity)
for [Country] in (' + @cols + ')
) p ';
Jalankan
execute(@query);
OUTPUT: