我正在尝试在T-SQL中执行一个支点,为每个SUM(INVOICE_AMOUNT)
返回2015年和2016年的CUST_ID
。
但是我使用的SQL会抛出错误:
'('
附近的语法不正确
我无法识别语法错误。有人可以告诉它有什么问题吗?
SELECT
H.CUST_ID, [2015], [2016]
FROM
(SELECT
H.INVOICE_AMOUNT, YEAR(H.INVOICE_DT)
FROM
BILLING_HEADER H) p
PIVOT
SUM(H.INVOICE_AMOUNT) FOR YEAR(INVOICE_DT) IN ([2015], [2016])) AS pvt
Year(INVOICE_AMOUNT)
有[2015]和[2016]的静态选项,所以不确定SQL有什么问题..
答案 0 :(得分:2)
PIVOT
运营商在FOR
关键字后需要column that contains the values that will become column headers。授予YEAR(INVOICE_DT)
别名并在FOR
SELECT H.CUST_ID, [2015], [2016]
FROM
(
SELECT H.INVOICE_AMOUNT, YEAR(H.INVOICE_DT) AS INVOICE_YEAR
FROM BILLING_HEADER H
) p
PIVOT
SUM(H.INVOICE_AMOUNT)
FOR INVOICE_YEAR in ([2015],[2016])
) as pvt
本质上,PIVOT运算符执行GROUP BY
操作,并通过从源表列中删除GROUP BY
运算符中使用的列来猜测应将哪个列放入PIVOT
子句。这种猜测不适用于功能。请参阅TSQL - Looking for code clarification