Hello, I need to do a pivot in sql server 2014 but failed. I read several forums but none of them helped. Below is my Table that I would like to pivot:
Below is my desired result:
This is what I have so far but have an error:
- DECLARE @Query AS NVARCHAR(MAX)
- DECLARE @PivotProductType AS NVARCHAR(MAX)
- --Get unique values of pivot column
- SELECT @PivotProductType= COALESCE(@PivotProductType + ',','') + QUOTENAME(ProductType)
- FROM (SELECT DISTINCT ProductType FROM tblAgentCommission) AS PivotColumn
- SELECT @PivotProductType
- --Create the dynamic query with all the values for
- --pivot column at runtime
- SET @Query =
- N'SELECT Country, ' + @PivotProductType + '
- FROM [dbo].[PivotColumn]
- PIVOT(CommissionRate)
- FOR ProductType IN (' + @PivotProductType + ')) AS P'
- SELECT @Query
- --Execute dynamic query
- EXEC sp_executesql @Query
(1 row(s) affected)
(1 row(s) affected)
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ')'.
Thanks in Advance.

Abhinav AbhishekRank #2,198 · 642 reputationPosted Jun 6, 2017, 5:51 AM EDT
Jes SieRank #1,285 · 1.3K reputationPosted Jun 6, 2017, 8:55 PM EDT
Manish KumarRank #1,622 · 956 reputationPosted Jun 8, 2017, 12:17 AM EDT
Jes SieRank #1,285 · 1.3K reputationPosted Jun 9, 2017, 1:24 AM EDT
Manish KumarRank #1,622 · 956 reputationPosted Jun 11, 2017, 11:20 PM EDT
Jes SieRank #1,285 · 1.3K reputationPosted Jun 15, 2017, 1:55 AM EDT
Manish KumarRank #1,622 · 956 reputationPosted Jun 15, 2017, 11:50 PM EDT
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts