I want to PIVOT my data on TradeMonth. below is how my data looks.
Lets call it table test_pivot
TradeMonth risk_hd risk_val
201808 abc 3.20364
201809 abc 3.155
201810 abc 3.58318
201811 abc 3.82526
201808 def 123191019
201809 def 107184352.9
201810 def 99110873.05
201811 def 104231257.9
If I pivot on risk_hd, I get the results however query is not working if I pivot on column TradeMonth. below is the query I am trying. I looked all around but nothing worked . Getting Syntax error near '201819' and near 'as'.
select P.risk_hd, P. , P.
(select * from Test_Pivot) as S
FOR TradeMonth IN (,  )
Appreciate your help in advance. thanks!
Unless it is a typo in your post rather than in your code, you are pivoting on 201811 and 201812 (which then would be the columns in the output), but are trying to sect non-existent columns 201809 and 201810.
I would think the query should be something like this:
(SELECT * FROM Test_Pivot) AS S
FOR TradeMonth IN (, ,,)
) AS P;
Not sure what you are looking for, but this will pivot on TradeMonth
drop table if exists #TestPivot
Create table #testPivot
risk_val numeric (12,2))
insert into #TestPivot values
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.TradeMonth)
FROM #TestPivot c
FOR XML PATH(''), TYPE
set @query = 'SELECT risk_hd, ' + @cols + ' from
for TradeMonth in (' + @cols + ')
) p '
Thanks for the input. that's a typo. I just ran your query. getting same error message.
Thanks Mike. This works like a charm!
Could you explain the code. What would be the value for @cols here. Didn't get that part.
There is no 201819 anywhere in the code that I posted. So not clear how you can get that error message. Check for typos.
Is this part of a larger query? Is there '201819' somewhere else?
the @Cols variable create columns out of all the distinct TradeMonths