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