The query below returns the SUM of quantities purchased over the last three years. My attempt was to wrap the whole block of code starting from WITH down to the WHERE of the Purchases query but I can not make the pivot work. I also wonder if the YEAR pivoted columns can be dynamically generated instead of passed using the FOR -> IN Pivot syntax.
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,-4,GETDATE()) AND ItemCode = 'Apple'
GROUP BY ItemCode, YEAR(DocDate)
ORDER BY ItemCode;
Result
+----------+------+------+
| ItemCode | Qty | Year |
+----------+------+------+
| Apple | 2300 | 2017 |
+----------+------+------+
| Apple | 1600 | 2018 |
+----------+------+------+
| Apple | 1000 | 2019 |
+----------+------+------+
| Apple | 1400 | 2020 |
+----------+------+------+
I would like to pivot the year column to get the following result:
+----------+------+------+------+------+
| ItemCode | 2017 | 2018 | 2019 | 2020 |
+----------+------+------+------+------+
| Apple | 2300 | 1600 | 1000 | 1400 |
+----------+------+------+------+------+