将本周数据与前几年的同一周进行比较

时间:2019-05-14 10:55:42

标签: sql sql-server

我有这张表,其中包含按商店和日期划分的销售额。

-------------------------------------------
P_DATE       -    P_STORE -  P_SALES
-------------------------------------------
2019-02-05   -     S1     -   5000
2019-02-05   -     S2     -   9850
2018-06-17   -     S1     -   6980
2018-05-17   -     S2     -   6590
..
..
..
-------------------------------------------

我想比较今年最后10周与前几年同一周的每家商店的销售总额。

我想要这样的结果:

---------------------------------------------------
Week   -   Store   -   Sales-2019   -   Sales2018
---------------------------------------------------
20     -   S1      -     2580       -     2430
20     -   S2      -     2580       -     2430
.
.
10     -   S1      -     5905       -     5214
10     -   S2      -     4789       -     6530
---------------------------------------------------

我已经尝试过了:

Select
[Week] = DATEPART(WEEK, E_Date),
[Store] = E_store
[Sales 2019] = Case when Year(P_date) = '2019' Then Sum (P_Sales)
[Sales 2018] = Case when Year(P_date) = '2018' Then Sum (P_Sales)

From
PIECE

Group by
DATEPART(WEEK, E_Date),
E_store

我需要你的帮助。

2 个答案:

答案 0 :(得分:0)

这是您要找的吗?

DECLARE @t TABLE (TransactionID INT, Week INT, Year INT, Amount MONEY)

INSERT INTO @t
(TransactionID, Week, Year, Amount)
VALUES
(1, 20, 2018, 50),
(2, 20, 2019, 20),
(3, 19, 2018, 35),
(4, 19, 2019, 40),
(5, 20, 2018, 70),
(6, 20, 2019, 80)

SELECT TOP 10 Week, [2018], [2019] FROM (SELECT Week, Year, SUM(Amount) As Amount FROM @t GROUP BY Week, Year) t
PIVOT  
(  
SUM(Amount)  
FOR Year IN ([2018], [2019])  
) sq
ORDER BY Week DESC

答案 1 :(得分:0)

此脚本将考虑10个星期,包括当前一周-

WITH wk_list (COMMON,DayMinus)
AS
(
SELECT 1,0 UNION ALL
SELECT 1,1 UNION ALL
SELECT 1,2 UNION ALL
SELECT 1,3 UNION ALL
SELECT 1,4 UNION ALL
SELECT 1,5 UNION ALL
SELECT 1,6 UNION ALL
SELECT 1,7 UNION ALL
SELECT 1,8 UNION ALL
SELECT 1,9
)
SELECT 
DATEPART(ISO_WEEK, P_DATE) WK,
P_STORE,
SUM(CASE WHEN YEAR(P_DATE) = 2019 THEN P_SALES ELSE 0 END) SALES_2019,
SUM(CASE WHEN YEAR(P_DATE) = 2018 THEN P_SALES ELSE 0 END) SALES_2018
FROM your_table
WHERE YEAR(P_DATE) IN (2019,2018)
AND DATEPART(ISO_WEEK, P_DATE) IN
(
    SELECT A.WKNUM-wk_list.DayMinus AS [WEEK NUMBER] 
    FROM wk_list
    INNER JOIN (
        SELECT 1 AS COMMON,DATENAME(ISO_WEEK,GETDATE()) WKNUM
    ) A ON wk_list.COMMON = A.COMMON
)
GROUP BY DATEPART(ISO_WEEK, P_DATE),P_STORE

但是,如果要排除当前星期,只需替换上面脚本中的以下部分

, wk_list (COMMON,DayMinus)
AS
(
SELECT 1,1 UNION ALL
SELECT 1,2 UNION ALL
SELECT 1,3 UNION ALL
SELECT 1,4 UNION ALL
SELECT 1,5 UNION ALL
SELECT 1,6 UNION ALL
SELECT 1,7 UNION ALL
SELECT 1,8 UNION ALL
SELECT 1,9 UNION ALL
SELECT 1,10
)