我有一个包含大学统计数据的表格,如下所示:
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;
考虑到您想要生成的输出,我不确定您是否需要使用
PIVOT
运算符。
您可以通过以下查询获得与上面的输出相当close的结果:
SELECT s.StatID
,UniversityID1 = SUM(CASE WHEN UniversityID = 1 THEN StatValue ELSE NULL END)
,UniversityID2 = SUM(CASE WHEN UniversityID = 2 THEN StatValue ELSE NULL END)
,UniversityID3 = SUM(CASE WHEN UniversityID = 3 THEN StatValue ELSE NULL END)
FROM StatsTable s
GROUP BY s.StatID
将会产生
StatID | UniversityID1 | UniversityID2 | UniversityID3
1 | 100 | 50 | NULL
2 | 90 | 55 | NULL
3 | 80 | NULL | NULL
它没有 StatID = 4 的最后一行,但我不确定为您提供什么值,因为所有值都统一为 NULL,并且输入表中没有 StatID = 4 数据。
如果你真的想要
PIVOT
语法,这里是:
SELECT StatID
,UniversityID1 = [1]
,UniversityID2 = [2]
,UniversityID3 = [3]
FROM
(SELECT StatID, UniversityID, StatValue FROM @table) up
PIVOT
(SUM(StatValue) FOR UniversityID IN ([1], [2], [3])) AS pvt
ORDER BY StatID;
(您缺少方括号 [])