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.

Manish KumarPosted Jun 16, 2017, 3:50 AM
Jes SiePosted Jun 15, 2017, 5:55 AM
Manish KumarPosted Jun 12, 2017, 3:20 AM
Jes SiePosted Jun 9, 2017, 5:24 AM
Manish KumarPosted Jun 8, 2017, 4:17 AM
Jes SiePosted Jun 7, 2017, 12:55 AM
Abhinav AbhishekPosted Jun 6, 2017, 9:51 AM