无法使SQL Pivot工作

时间:2012-04-10 21:12:39

标签: sql-server-2008

我有一个临时表,其中包含零件类别和相关的零件成本:

#part_costs
part_cat  |  part_cost
tire      |  0
fuel      |  24
wheel     |  34

#part_costs中的行数和值是动态的。我正在尝试创建一个支点,所以我将拥有(与列的顺序无关):

tire | fuel | wheel
0    | 24   | 34

我创建了一个表变量,用于保存包含名称的部件类别变量NVARCHAR(2000)

"[fuel],[tires],[wheel]"

到目前为止我的支点

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

然而我无法让它发挥作用。我可以运行我的存储过程,它位于,但是当我执行我的存储过程时,我收到以下错误:Incorrect syntax near the keyword 'FOR'.

以前我有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虽然这样我甚至无法运行我的存储过程,因为我Incorrect syntax near the keyword 'for'.

1 个答案:

答案 0 :(得分:4)

您必须在FOR之前使用聚合函数(例如AVG,MAX)。另外,请确保正确列出列值名称,即轮胎与轮胎不同。

SELECT [fuel],[tire],[wheel]
FROM (
    SELECT part_cat, part_cost
    FROM #part_costs
) p
PIVOT
(
    Avg([part_cost]) FOR part_cat IN ( [fuel],[tire],[wheel] )
) AS pvt