I have a normalized table that I'd like to 'Flatten' dynamically.
Picture below for example input and output. The columns need to be fetched dynamically, it can't be hard coded.
So far, this is what I'm working on.
`DECLARE @Query nvarchar(MAX) = '';`
DECLARE @columns nvarchar(1000) = '';`
Select @cols = @cols + QUOTENAME(Food) + ',' FROM (select distinct Food from tblPeopleFoods ) as tmp
Select @cols = substring(@cols, 0, len(@cols))
At this point, I have the properly comma separated string for my column names.
I'm hung up on the PIVOT
query to flag each person 1 or 0 for having each food.
This is what I have so far
set @query =
'SELECT * from
(
select Person, Food from tblPeopleFoods
) src
pivot
(
count(*) for Person in (' + @cols + ')
) piv