Sunday, 24 January 2016

SQL pivot without aggregration

Pivot data to return the first two country entries for each person.

select * from Source_Table;
select * from
( select
person,
country,
'country' + cast(rank()
over (partition by person order by id)
as varchar(10))
as countryrank
from dbo.Source_Table) as rankedSource
pivot
( max (country) for countryrank in (country1, country2)) as pivottable;
view raw sql-pivot.sql hosted with ❤ by GitHub