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

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;

08-28 03:22