我正在使用此查询获取过去12个月的销售额。
SELECT *
FROM (SELECT
gp_etablissement [ETABLISSEMENT],
datename(month, dateadd(m,-1,getdate())) [Month],
COUNT(1) [Sales Count]
FROM PIECE
GROUP BY gp_etablissement,
datename(month, dateadd(m,-1,getdate()))) AS MontlySalesData
PIVOT( SUM([Sales Count])
FOR Month IN ([January],[February],[March],[April],[May],
[June],[July],[August],[September],[October],[November],
[December])) AS MNamePivot
我收到此错误:
每个GROUP BY表达式必须至少包含一列 外部参考。
我更改了分组依据中的许多列,但存在相同的问题。
答案 0 :(得分:0)
使用以下代码消除错误。当分组依据使用日期部分时,数据透视表不适用于子查询。
;WITH CTE
AS
(
SELECT
gp_etablissement [ETABLISSEMENT],
datename(month, dateadd(m,-1,getdate())) [Month],
COUNT(1) [Sales Count]
FROM PIECE
GROUP BY gp_etablissement,
datename(month, dateadd(m,-1,getdate()))
)
SELECT *
FROM CTE
PIVOT( SUM([Sales Count])
FOR Month IN ([January],[February],[March],[April],[May],
[June],[July],[August],[September],[October],[November],
[December])) AS MNamePivot