-4

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 |
+----------+------+------+------+------+

2 Answers2

1

You can make use of Pivot function in SQL server:

Demo

SELECT * FROM TABLE1
PIVOT(MIN(QTY) FOR [YEAR] IN ([2017], [2018], [2019], [2020])) PIVOT_TABLE;
Atif
  • 2,011
  • 9
  • 23
1

If the OP prefers conditional aggregation to SQL Server PIVOT

SELECT [ItemCode],
  max(case when [YEAR]=2017 then QTY else null end) [2017],
  max(case when [YEAR]=2018 then QTY else null end) [2018],
  max(case when [YEAR]=2019 then QTY else null end) [2019],
  max(case when [YEAR]=2020 then QTY else null end) [2020]
FROM TABLE1
group by [ItemCode];
SteveC
  • 5,955
  • 2
  • 11
  • 24