Skip to content
Advertisement

Query and Pivot Column for the last last 3 Years SQL

My need is to retrieve sell data from and pivot the last three years and sum the quantities. See example below. I wonder how to do it. I read that SQL pivot is the way to go, but I can’t figure out how to deal with pivoting “automatically” N number of years in the past.

INPUT

+----------+----------+------+
| ItemCode | Quantity | Date |
+----------+----------+------+
|     A    |    100   | 2017 |
+----------+----------+------+
|     B    |    200   | 2017 |
+----------+----------+------+
|     B    |    200   | 2017 |
+----------+----------+------+
|     A    |    50    | 2018 |
+----------+----------+------+
|     A    |    170   | 2018 |
+----------+----------+------+
|     A    |    75    | 2019 |
+----------+----------+------+
|     B    |    10    | 2019 |
+----------+----------+------+

OUTPUT

+---+------+------+------+
|   | 2017 | 2018 | 2019 |
+---+------+------+------+
| A |  100 |  220 |  75  |
+---+------+------+------+
| B |  400 |   -  |  10  |
+---+------+------+------+

Advertisement

Answer

You can try PIVOT opertor in SQL Server. I am applying YEAR function to get current year and subtracting 3 years from it to filter the dates.

    DECLARE @table TABLE(Itemcode CHAR(1), Quantity int, datevalue int)

  INSERT INTO @TABLE VALUES
  ('A',100   ,2017 ),
  ('B', 200  ,2017 ),
  ('B', 200  ,2017 ),
  ('A', 50   ,2018 ),
  ('A', 170  ,2018 ),
  ('A', 75   ,2019 ),
  ('B', 10   ,2019 ),
  ('A', 10   , 2015);


  SELECT Itemcode,[2017],[2018],[2019]
  FROM
  (SELECT * FROM @table WHERE datevalue >= (YEAR(GETDATE()) - 3)) as t
  PIVOT
  (
  SUM(Quantity) FOR dateValue IN ([2017],[2018],[2019])
  ) as pvt


+----------+------+------+------+
| Itemcode | 2017 | 2018 | 2019 |
+----------+------+------+------+
| A        |  100 | 220  |   75 |
| B        |  400 | NULL |   10 |
+----------+------+------+------+
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement