SQL Server 今年的WTD与去年的WTD比较

h9a6wy2h  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(132)

我想用去年同一周的销售数据来确定本年度WTD销售数据的增长情况。
因此,如果本周是星期一、星期二、星期三,我将尝试比较去年同一周的星期一、星期二、星期三,以确定销售增长。这在某种意义上需要是动态的,因为它将在每日报告中运行,在前一天结束WTD,并通过SSRS通过电子邮件发送给各个用户。
我已经做了大量的在线搜索,并尝试了几次迭代,所有的不良影响。
最近的一次尝试是

SELECT 
      [storeid],
      SUM([Sales]) as [2021SalesWTD]
    FROM [dbo].[DailySales2021]
    WHERE CONVERT(date, [date]) >=  DATEADD(DAY, 1-DATEPART(dw, DATEADD(YEAR,-1,GETDATE())),  CONVERT(date, DATEADD(YEAR,-1,GETDATE())))
         AND DATEADD(DAY, 8-DATEPART(dw, DATEADD(YEAR,-1,GETDATE())), CONVERT(date, DATEADD(YEAR,-1,GETDATE())))
    GROUP BY storeid

这将返回整个星期

jhdbpxl9

jhdbpxl91#

尝试变量声明可能会对您有所帮助。
这是我起草的东西:

--Get today's date, find the day of the week (1 indexed from Sunday) and subtract. Add 2 to balance this offset
DECLARE @MondayThisYear AS DATE = CAST(GETDATE()-DATEPART(WEEKDAY, GETDATE())+2 AS DATE)
--Get the date a year ago. I haven't checked for leap year, add it if you need it
DECLARE @DateLastYear AS DATE = @MondayThisYear-365
--Same idea as MondayThisYear, but using the date from last year
DECLARE @MondayLastYear AS DATE = CAST(@DateLastYear-DATEPART(WEEKDAY, @DateLastYear)+2 AS DATE)
--The number of days that have passed in this working week
DECLARE @WorkingDays AS INT = DATEDIFF(d, @MondayThisYear, GETDATE())

SELECT [insert columns]
FROM [insert table name]
WHERE   ([date column]>@MondayThisYear AND [date column]<GETDATE()) OR
        ([date column]>@MondayLastYear AND [date column]<@MondayLastYear + @WorkingDays)

你可能还需要检查我是如何定义上一年的日期的。在最坏的情况下,你可能会得到一个星期的错误,但我不认为这是可以避免的,因为日历的结构。

相关问题