I was trying a PIVOT query and have a hard time understanding how we can assign multiple values to a variable.
My colleague pointed me to this query. This solved my problem but I am unable to understand this line
COALESCE(@Pivot_Column + ',', '') + QUOTENAME(Year)
Actually when a variable is assigned to a select with multiple values that last value is taken.
But if we observe all values are returned with above line.
Can someone help me understand?
DECLARE @Pivot_Column [nvarchar](max);
DECLARE @Query [nvarchar](max);
/*Select Pivot Column*/
SELECT @Pivot_Column = COALESCE(@Pivot_Column + ',', '') + QUOTENAME(Year)
FROM
(SELECT DISTINCT [Year] FROM Employee) Tab
/* Create dynamic query */
SELECT @Query = 'SELECT Name, ' + @Pivot_Column +
'FROM
(SELECT Name, [Year], Sales FROM Employee) Tab1
PIVOT
(SUM(Sales) FOR [Year] IN ('+@Pivot_Column+')) AS Tab2
ORDER BY Tab2.Name'
/* Execute query */
EXEC sp_executesql @Query