我遇到此错误
'PRINTING_DATE'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中
但是通过使用OVER PARTITION BY
,我希望此问题不会出现,为什么我仍然出现此错误?
DECLARE @REPORT AS NVARCHAR(50) = '2019-06-19 00:00:00.000'
SELECT
SUM(CASE
WHEN (P_DATE < @REPORT AND P_DATE > DATEADD(DAY, -7, @REPORT))
THEN QTY_PICKED
ELSE 0
END) OVER (PARTITION BY PLANT, PARTS, P_DATE) AS SHIPPED,
SUM(CASE
WHEN E_DATE > @REPORT AND E_DATE < DATEADD(DAY, 7, @REPORT)
THEN QTY_MII
ELSE 0
END) - SUM(CASE
WHEN E_DATE > @REPORT AND E_DATE < DATEADD(DAY, 7, @REPORT)
THEN QTY_PICKED
ELSE 0
END) AS TO_SHIP
FROM
TABLE1 T1
INNER JOIN
TABLE2 T2 ON T1.DELIVERY = T2.DELIVERY
WHERE
PLANT = 'XXX'
答案 0 :(得分:0)
正如HoneyBadger指出的那样,第一个SUM中只有一个“ OVER PARTITION BY”,而第二个SUM中则没有。
尝试以下简化版本:
DECLARE @T1 TABLE(PLANT INT,PARTS INT,P_DATE DATE,QTY1 INT, QTY2 INT)
INSERT INTO @T1 VALUES(1,1,'2019-07-03',40,60)
INSERT INTO @T1 VALUES(1,1,'2019-07-03',50,80)
SELECT
SUM(QTY1) OVER (PARTITION BY PLANT, PARTS, P_DATE) AS SHIPPED
,SUM(QTY1) OVER (PARTITION BY PLANT, PARTS, P_DATE) -
SUM(QTY2) OVER (PARTITION BY PLANT, PARTS, P_DATE) AS TOSHIP
,SUM(QTY1) - SUM(QTY2) AS TOSHIP2
FROM @T1
WHERE PLANT = 1
这将引发错误: 在选择列表中,列“ @ T1.PLANT”无效,因为该列未包含在聚合函数或GROUP BY子句中。 如果您注释/删除该行
,SUM(QTY1) - SUM(QTY2) AS TOSHIP2
它将产生结果。 顺便说一句:在此示例中,错误也指向第一个SUM,但这不是问题。
答案 1 :(得分:0)
目前还不清楚您要做什么。但我可以提供一个提示:如果您的结果集是返回一行的聚合,则窗口函数没有用。
因此,您可能需要这样做:
SELECT SUM(CASE WHEN (P_DATE < @REPORT AND P_DATE > DATEADD(DAY, -7, @REPORT))
THEN QTY_PICKED
ELSE 0
END) AS SHIPPED,
(SUM(CASE WHEN E_DATE > @REPORT AND E_DATE < DATEADD(DAY, 7, @REPORT)
THEN QTY_MII
ELSE 0
END) -
SUM(CASE WHEN E_DATE > @REPORT AND E_DATE < DATEADD(DAY, 7, @REPORT)
THEN QTY_PICKED
ELSE 0
END)
) AS TO_SHIP
FROM TABLE1 T1 INNER JOIN
TABLE2 T2
ON T1.DELIVERY = T2.DELIVERY
WHERE PLANT = 'XXX';
当然,您可能希望返回不止一行的聚合查询:
SELECT PLANT, PARTS, P_DATE,
SUM(CASE WHEN (P_DATE < @REPORT AND P_DATE > DATEADD(DAY, -7, @REPORT))
THEN QTY_PICKED
ELSE 0
END) AS SHIPPED,
(SUM(CASE WHEN E_DATE > @REPORT AND E_DATE < DATEADD(DAY, 7, @REPORT)
THEN QTY_MII
ELSE 0
END) -
SUM(CASE WHEN E_DATE > @REPORT AND E_DATE < DATEADD(DAY, 7, @REPORT)
THEN QTY_PICKED
ELSE 0
END)
) AS TO_SHIP
FROM TABLE1 T1 INNER JOIN
TABLE2 T2
ON T1.DELIVERY = T2.DELIVERY
WHERE PLANT = 'XXX'
GROUP BY PLANT, PARTS, P_DATE;