最近 3 年的查询和数据透视列 SQL

Query and Pivot Column for the last last 3 Years SQL

我需要检索过去三年的销售数据和数据透视表,并对数量求和。请参见下面的示例。我不知道该怎么做。我读到 SQL 枢轴是要走的路,但我无法弄清楚如何处理过去 "automatically" N 年数的枢轴。

输入

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

输出

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

试试下面的逻辑-

SELECT ItemCode,
SUM(CASE WHEN Date = 2017 THEN Quantity ELSE 0 END) AS '2017',
SUM(CASE WHEN Date = 2018 THEN Quantity ELSE 0 END) AS '2018',
SUM(CASE WHEN Date = 2019 THEN Quantity ELSE 0 END) AS '2019'
FROM your_table
GROUP BY ItemCode 

您可以在 SQL 服务器中尝试 PIVOT 运算符。我正在应用 YEAR 函数来获取当前年份并从中减去 3 年来过滤日期。

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

基于 Venkataraman R 答案。如果您希望在出现时添加年份,您可以使用一些动态代码:

DROP TABLE IF EXISTS #Temp
CREATE TABLE #temp
    ( ItemCode char(1)
    , Quantity int
    , [Date] int
    )
INSERT INTO #temp
VALUES    ('A',100,2017)
        , ('B',200,2017)
        , ('B',200,2017)
        , ('A',50,2018)
        , ('A',170,2018)
        , ('A',75,2019)
        , ('B',10,2019);

DECLARE 
    @columns nvarchar(MAX) = ''
    , @sql nvarchar(MAX);

SELECT 
    @columns += QUOTENAME([Date]) + ','
FROM (
    SELECT [Date]
    FROM #temp
    GROUP BY [Date]) AS t
ORDER BY 
    [Date];

SET @columns = LEFT(@columns, LEN(@columns) - 1);

PRINT @columns;

SET @sql = '
SELECT 
    *
FROM #temp AS t
PIVOT(
    SUM(Quantity)
    FOR [Date] IN(
    ' + @columns + '
        )) AS pvt'

EXECUTE sp_executesql @sql