你如何比较当年和去年同一周的同一天?

时间:2016-10-10 09:04:36

标签: sql tsql

大多数零售商使用商品日历作为销售报告,可以帮助他们在当年和上一年的同一周找到同一天。

例如今天' 2016-10-10'星期一即可。去年; 2015年,同一周,周一是2015-10-12'

我们如何通过SQL查询来捕获它并在一个表中显示它们?

2 个答案:

答案 0 :(得分:2)

你有很多date functions可以做到这一点:

或者快捷方式只需减去52周就可以了:

DATEADD(week, -52, some_Date)

答案 1 :(得分:0)

SELECT t1.data AS data1, t1.date AS date1,
  t2.data AS data2, t2.date AS date2
FROM table t1
LEFT OUTER JOIN table t2 
  ON ( DATEPART(week,t1.date) = DATEPART(week,t2.date)
     AND DATEPART(weekday,t1.date) = DATEPART(weekday,t2.date) )
WHERE DATEPART(year,t1.date) = 2016 
      AND DATEPART(year,t2.date) = 2015

如果该查询太慢,您可以使用计算列来协助它:

ALTER TABLE table ADD year AS DATEPART(year,date) PERSISTED;
ALTER TABLE table ADD week AS DATEPART(week,date) PERSISTED;
ALTER TABLE table ADD weekday AS DATEPART(weekday,date) PERSISTED;

CREATE INDEX idx_datecalc ON table (year, week, weekday);

现在调整以上查询:

[...]
LEFT OUTER JOIN table t2 
  ON ( t1.week = t2.week) ...etc.