I want to SUM the quantities of a purchased item but can not get the result using WITH (procedural and I was thinking simpler)
WITH Purchases (ItemCode, Quantity, DocDate)
AS
(
SELECT ItemCode, Quantity, OPOR.DocDate
FROM OPOR INNER JOIN POR1 ON OPOR.DocEntry = POR1.DocEntry
WHERE Canceled = 'N'
GROUP BY OPOR.DocDate,ItemCode,QuantitY
)
SELECT ItemCode, SUM(Quantity) AS Qty, YEAR(DocDate) AS Year
FROM Purchases
WHERE DocDate > DATEADD(YEAR,-3,GETDATE()) AND ItemCode = '01.BEE.05'
GROUP BY ItemCode,DocDate
ORDER BY ItemCode;
This is what I get right know.
+-------------+--------+--------+
| "ItemCode" | "Qty" | "Year" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2018" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2019" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2019" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2019" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2019" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2019" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2019" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2020" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2020" |
+-------------+--------+--------+
| "01.BEE.05" | "9000" | "2020" |
+-------------+--------+--------+
| "01.BEE.05" | "3000" | "2020" |
+-------------+--------+--------+
This is what I want to end up with
+-------------+---------+--------+
| "01.BEE.05" | "3000" | "2018" |
+-------------+---------+--------+
| "01.BEE.05" | "18000" | "2019" |
+-------------+---------+--------+
| "01.BEE.05" | "18000" | "2020" |
+-------------+---------+--------+
You're grouping by the DocDate
instead of YEAR(DocDate)
like you have in the select list:
WITH Purchases (ItemCode, Quantity, DocDate)
AS
(
SELECT ItemCode, Quantity, OPOR.DocDate
FROM OPOR INNER JOIN POR1 ON OPOR.DocEntry = POR1.DocEntry
WHERE Canceled = 'N'
GROUP BY OPOR.DocDate,ItemCode,QuantitY
)
SELECT ItemCode, SUM(Quantity) AS Qty, YEAR(DocDate) AS Year
FROM Purchases
WHERE DocDate > DATEADD(YEAR,-3,GETDATE()) AND ItemCode = '01.BEE.05'
GROUP BY ItemCode, YEAR(DocDate)
-- Here -----------^
ORDER BY ItemCode;
将您的组更改为此
GROUP BY ItemCode,YEAR(DocDate)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.