I have a CTE query set up like output of 1 is the input of next query and have a PIVOT in between. What is the correct syntax to use the dynamic PIVOT sql in cte2 in this template. I get error when I use it in the cte2. I am using SQL Server
with cte1 as
( SELECT * FROM table1)
,
cte2 as
( --Dynamic Pivot of row values to column names using SET and DECLARE
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
-- Get the distinct values from the column to be pivoted
SELECT @cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME([type])
FROM cte1
FOR XML PATH('')
), 1, 1, '')
-- Build the dynamic SQL query
SET @query = 'SELECT account_id, country,' + @cols + '
FROM
(
SELECT TOP 100 o.account_id, o.country, type, amount
FROM cte1 as o
) x
PIVOT
(
sum(amount)
FOR [type] IN (' + @cols + ')
) p'
-- Execute the dynamic SQL query
EXEC sp_executesql @query
--end of pivot query
), --end of cte2
cte3 as (
SELECT *
FROM cte2 --output data of pivot query to be used as input here
WHERE type = 'New Business'
) --end of cte3 for New Business