比较同一周不同年份的数据

时间:2019-05-13 14:04:33

标签: sql-server

我正在尝试将过去10周与两年的数据进行比较:2019和2018。 在这种情况下,一周必须从星期一开始,到星期日结束。

-------------------------------
WEEK - STORE - D-2019 - D-2018
-------------------------------
20      S1     1580      2500
20      S2     2690      4500
..
19
18
17
10
-------------------------------

[WEEK] = DATEPART(ISO_WEEK, GP_DATEPIECE),
[STORE] = ET_LIBELLE,
CASE WHEN (YEAR = 2019) THEN [D-2019],
CASE WHEN (YEAR = 2018) THEN [D-2018],

GROUP BY
DATEPART(ISO_WEEK, GP_DATEPIECE),
ET_LIBELLE

请问有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试一下。

SELECT (DATEPART(WEEK,GETDATE()) - ID) [WEEK], ET_LIBELLE [STORE], [2018] AS [D-2018], [2019] AS [D-2018]
FROM 
    (SELECT TOP 10 ROW_NUMBER() OVER(ORDER BY GP_DATEPIECE) -1 AS ID FROM TestTable) W
    LEFT JOIN 
        (SELECT DATEPART(YEAR, GP_DATEPIECE) [Year], DATEPART(WEEK,GP_DATEPIECE) [Week], SUM(D) AS D 
        FROM TestTable
        WHERE GP_DATEPIECE > DATEADD(YEAR,-1,DATEADD(WEEK, -10, GETDATE()))
        GROUP BY ET_LIBELLE, DATEPART(YEAR, GP_DATEPIECE), DATEPART(WEEK,GP_DATEPIECE)) T ON DATEPART(WEEK,GETDATE()) - W.ID = T.[Week]
PIVOT(SUM(D) FOR [Year] IN ([2018], [2019]) ) PVT
ORDER BY [WEEK] DESCC