I used the above code from the link. But I recieve an error as
Msg 8156, Level 16, State 1, Line 14 The column 'Factory' was specified multiple times for 'p'
Efficiently convert rows to columns in sql server
Here is my table :
TEST
ID score Check TotalofScore
------ ----- ------- ------------
867439 1 factory 1
867439 1 Plant 1
867442 1 factory 1
867442 1 Plant 1
923991 1 Warehouse 1
923991 1 Plant 1
923930 1 factory 1
923930 1 Plant 1
923101 1 Warehouse 1
923101 1 Plant 1
Here's my try
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = Stuff((SELECT ',' + Quotename([check])
FROM TEST
GROUP BY [Check],
[ID]
ORDER BY [ID]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = N'SELECT ' + @cols + N' from
(SELECT TEST.[ID],
Score,
[check],
[Total Of Score] = Count(TEST.Score) over(partition by [ID], [score], [check])
FROM TEST) T
pivot
(
SUM (T.[score])
for T.[check] in (' + @cols + N') ) p '
EXEC Sp_executesql @query;
Expected Result :
ID TotalofScore factory Plant Warehouse
------ ------------ ------- ----- ---------
867439 1 1
867439 1 1
867442 1 1
867442 1 1
923991 1 1
923991 1 1
923930 1 1
923930 1 1
923101 1 1
923101 1 1
As mentioned in Error You cannot specify same column name more than once in
Pivot
like..pivot (SUM (T.[score]) for T.[check] in ([factory,[Plant],[factory]..))p
Change your
@cols
initialization like thisOr
Update : To convert the Dynamic Pivot into procedure and insert the result into new table
Remove the
Id
fromGROUP BY
andORDER By
clause. So that you get theDISTINCT
Check columns.