I have a temporary table that contains a part category and the associated part cost:
#part_costs
part_cat | part_cost
tire | 0
fuel | 24
wheel | 34
The number of rows and the values within #part_costs are dynamic. I am trying to create a pivot so I will have (doesn’t matter the order of the columns):
tire | fuel | wheel
0 | 24 | 34
I created a table variable that holds the part category variable NVARCHAR(2000) that holds the names:
"[fuel],[tires],[wheel]"
So far for my pivot I have
SELECT [fuel],[tires],[wheel] FROM (SELECT part_cat, part_cost FROM #part_costs ) p PIVOT ( [part_cost] FOR part_category IN ( [fuel],[tires],[wheel] )) AS pvt
Yet I can’t get this to work. I can run my stored procedure, that this is located in, yet when I execute my stored procedure I get the following error: Incorrect syntax near the keyword 'FOR'.
Previously I had select 'part_cost' as costs, @part_names from (select part_cat, part_cost from #part_costs) as p PIVOT (part_cost for part_cat in (@part_names)) as PivotTable though with this I wasn’t even able to run my stored procedure as I got Incorrect syntax near the keyword 'for'.
You have to use an Aggregate function (e.g. AVG, MAX) before the FOR. Also make sure to list the column value names correctly i.e. tires is not same as tire.