我正在研究Datacamp T-SQL课程,由于某种原因,我不知道要使用数据透视表。
开始查询是:
SELECT CategoryID, AVG(UnitPrice) AS Price
FROM Products
GROUP BY CategoryID;
结果是:
CategoryID Price
----------------------
1 37.9791
2 23.0625
3 25.1600
4 28.7300
5 20.2500
6 54.0066
7 32.3700
8 20.6825
我想要的结果
Per Category 1 2 3 4 5 6 7 8
Average Unit Price 37.98 23.06 25.16 28.73 20.25 54.01 32.37 20.68
我写的代码:
SELECT *
FROM
(SELECT CategoryID, AVG(UnitPrice)
FROM DBO.Products) AS test
PIVOT
(UnitPrice
FOR CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])) AS PivotTable
GROUP BY
CategoryID
但是然后我得到了错误
[42000] [Microsoft] [SQL Server的ODBC驱动程序17] [SQL Server]关键字'FOR'附近的语法不正确。 (156)(SQLExecDirectW)
我还尝试了枢轴上的AVG(UnitPrice)
。
然后生成此错误:
[42S22] [Microsoft] [SQL Server的ODBC驱动程序17] [SQL Server]无效的列名'UnitPrice'。 (207)(SQLExecDirectW)
我已经在这上面呆了一段时间了,我也不知道在哪里看。如果有人可以指出正确的方向,请先谢谢。
答案 0 :(得分:4)
假设Products
中的列多于所示的列,我认为您想要这样做:
SELECT * FROM
(SELECT CategoryID, UnitPrice
FROM DBO.Products) as test
PIVOT (
AVG(UnitPrice) FOR
CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable
PIVOT
隐藏了一个不需要重复的显式分组。如果Products
仅包含CategoryID
和UnitPrice
,我们可以直接使用它,而不是test
子查询
答案 1 :(得分:0)
我将删除GROUP BY
:
SELECT *
FROM (SELECT CategoryID, UnitPrice FROM DBO.Products) as test
PIVOT (AVG(UnitPrice) FOR CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable
答案 2 :(得分:0)
SELECT CategoryID, [1], [2], [3], [4], [5], [6], [7], [8] FROM
(SELECT price, CategoryID from dbo.Products) x
PIVOT (
MAX(price) FOR
CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable
答案 3 :(得分:0)
这有效:
SELECT 'Average Unit Price' AS 'Per Category',
[1], [2], [3], [4], [5], [6], [7], [8]
FROM
(SELECT CategoryID, UnitPrice
FROM dbo.Products) AS SourceTable
PIVOT
(
AVG(UnitPrice)
FOR CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable;