我有一个包含大学统计数据的表格,如下所示:

StatID | UniversityID | StatValue
1      | 1            | 100
2      | 1            | 90
3      | 1            | 80
1      | 2            | 50
2      | 2            | 55

我想要一个查询返回这样的内容:

(Rows are StatIDs, Columns are UniversityIDs)
StatID | 1             | 2             | 3
1      | 100           | 50            | NULL
2      | 90            | 55            | NULL
3      | 80            | NULL          | NULL

这是我的查询:

SELECT StatID, 1, 2, 3
FROM 
    (SELECT StatID, UniversityID, StatValue FROM @table) up
PIVOT 
    (MAX(StatValue) FOR UniversityID IN (1, 2, 3)) AS pvt
ORDER BY StatisticID;

我收到错误FOR UniversityID IN (1,说:

Incorrect syntax near '1'. Expecting ID, QUOTED_ID, or '.'.

我究竟做错了什么?int作为列标题?

我将使用它来处理约 260,000 行(约 300 列和约 3,000 行)

答案

您的 IN 语法错误:

SELECT StatisticID, 1, 2, 3
FROM
     (SELECT StatisticID, UniversityID, Value
     FROM @table) up
PIVOT
     (MAX(Value) FOR UniversityID IN ([1], [2], [3])) AS pvt
ORDER BY StatisticID;

来自: stackoverflow.com