You are here:Home » SQL Server General » Changing Rows to Columns Using PIVOT - Dynamic columns for Pivoting in SQL Server

Changing Rows to Columns Using PIVOT - Dynamic columns for Pivoting in SQL Server

We have seen example of Changing Rows to Columns Using PIVOT. Hope you liked that post and you enjoyed a lot also. As we know that we need to hard-code the values for pivoting which we have made for color values. For the values updates in table or whenever values changed in the table for the column which we use in pivot then we have to update the script as per that otherwise it won't work or do not give correct information. Also, I got the same comment from a user in the post which you can reach from the above link.

I am going to explain the same scenario and the resolution for the same, but you need to read original post properly. So requesting you to read it first if you did not read. So whenever we add new color values in the table, the same pivot query does not return information about the new values. So let us add new value and prepare the query and run.

-- Inserting one more record in existing table created in earlier post
INSERT INTO TblPivot
(
 ItemCode,
 ItemName,
 ItemColour
)
SELECT 
 6,
 'Samsung Mobile',
 'Silver'
After adding above new value, the pivot query which used in earlier post does not return right result set. Here's the solution for such type of issue we need to make the query with dynamic columns as following, We have got distinct values and embedded as comma separated using ‘[‘ and ‘]’. To make dynamic we can use COALESCE or FOR XML PATH.
DECLARE @ColourColumn varchar(200)
DECLARE @sql varchar(1000)

CREATE TABLE #Colours
(
Colour varchar(500)
)

INSERT INTO #Colours (Colour)
SELECT 
 DISTINCT '[' + ItemColour + ']' 
FROM TblPivot

-- Creating Column Names for Pivot
SELECT @ColourColumn = COALESCE(@ColourColumn + ',', '') +
Colour
FROM #Colours

/*
--OR
SET @ColourColumn = (SELECT  SUBSTRING(
 (SELECT DISTINCT ',' + Colour
  FROM #Colours
  FOR XML PATH('')),2,200000) 
 )
*/

DROP TABLE #Colours

SET @sql = 
'
 SELECT
 *
  FROM
  (
  SELECT 
   ItemCode, 
   ItemName, 
   ItemColour
  FROM TblPivot
  ) AS P
 PIVOT
 (
   Count(ItemName) FOR ItemColour IN ('+@ColourColumn+')
 ) AS pv
'
EXEC (@sql)

I want you to share your ideas for such issues which you faced and the resolutions for the same.