我有一个[Year / Week]列,我希望以此为基础具有12周(包括当周)在内的窗口。例如:如果当前星期是第5周,则无论当前日期是星期一还是星期五,我都希望显示从第5周到第16周的窗口。
我尝试在下面的代码中设置一些数字来调整此窗口,但我相信必须有更好的方法。
CREATE TABLE #DATES ([Year/Week] VARCHAR(MAX))
INSERT INTO #DATES ([Year/Week]) VALUES
('2019/W01'),('2019/W02'),('2019/W03'),('2019/W04'),('2019/W05')
,('2019/W06'),('2019/W07'),('2019/W08'),('2019/W09'),('2019/W10')
,('2019/W11'),('2019/W12'),('2019/W13'),('2019/W14'),('2019/W15')
,('2019/W16'),('2019/W17'),('2019/W18'),('2019/W19'),('2019/W20')
,('2019/W21'),('2019/W22'),('2019/W23'),('2019/W24'),('2019/W25')
,('2019/W26'),('2019/W27'),('2019/W28'),('2019/W29'),('2019/W30')
,('2019/W31'),('2019/W32'),('2019/W33'),('2019/W34'),('2019/W35')
SELECT DISTINCT
CONVERT(INT, LEFT([Year/Week], 4)) AS [Year]
,CONVERT(INT, RIGHT([Year/Week], 2)) AS [Week]
,dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)), dateadd (year,
CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4 -
datepart(dw, dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)),
dateadd (year, CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4) + 1 AS
[Week Date]
FROM #DATES
WHERE dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)), dateadd (year,
CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4 -
datepart(dw, dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)),
dateadd (year, CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4) + 1
BETWEEN GETDATE() - 3 AND GETDATE() + 81
ORDER BY [Year], [Week]
答案 0 :(得分:3)
我建议您使用Calendar table进行报告。
此后,只需进行少量查询即可轻松获得相同的结果
select Year, Week
from Auxiliary.Calendar
where Date between GetDate() and DATEADD(MONTH, 4, GetDate())
这里是DBFiddle
答案 1 :(得分:0)
您似乎正在使用ISO周。您应该可以使用类似以下的命令“按字母顺序”执行比较:
select [Year/Week] from #DATES
where [Year/Week] between
format(getdate() - 3, 'yyyy/\W') + format(datepart(iso_week, getdate() - 3), '0#') and
format(getdate() + 81, 'yyyy/\W') + format(datepart(iso_week, getdate() + 81), '0#')
order by [Year/Week];
确保周数与您的周数匹配。
不幸的是,我没有想到避免重复日期表达式的方法。也许还有一些更紧凑的东西。像这样的表达式可能更适合在Year/Week
列上使用索引。