'SQL Pivot with Text Values

First question posted here so apologies if it is the wrong place!

I'm attempting to pivot data in SSMS based on the below sample data that i have as an example

enter image description here

Ideally the result that i am after would be to have the person listed in the first column, then the number of instances of that person in the data as row headers, with the outcome of each visit (based on date order) as the value - like the below

enter image description here

Any help would be greatly appreciated!

Thanks Kieran



Solution 1:[1]

Hello try this is solved in Oracle.I don t know what database are you using Hope it helps.

with flo as (
select a.*, row_number()over(partition by person order by (select 1 from dual) )as rn 
from yourtable a)
select person, max(case when rn=1 then outcome end )as "1" ,
max(case when rn=2 then outcome end )as "2",
max(case when rn=3 then outcome end )as "3",
max(case when rn=4 then outcome end )as "4",
max(case when rn=5 then outcome end )as "5",
max(case when rn=6 then outcome end )as "6",
max(case when rn=7 then outcome end )as "7"
from flo
group by person;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Florin