如何在 MSSQL 中获取最近 6 周的开始日期和结束日期
Posted
技术标签:
【中文标题】如何在 MSSQL 中获取最近 6 周的开始日期和结束日期【英文标题】:how to get last 6 week start date and end date in MSSQL 【发布时间】:2021-02-18 08:05:22 【问题描述】:例如,今天是 2021 年 2 月 18 日,那么开始日期是 2021 年 2 月 14 日,结束日期是 2021 年 2 月 20 日。
过去 3 周的这些方式将是:
week | start date | End Date |
---|---|---|
Week 1 | 14 Feb 2021 | 20 Feb 2021 |
week 2 | 7 Feb 2021 | 13 Feb 2021 |
week 3 | 31 Jan 2021 | 6 Feb 2021 |
第 1 周是当前周,第 2 周是第 1 周的前一周,依此类推
我已经尝试了以下脚本:
select cast(DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()) as date) [Week1 start]
select cast(DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate()) as date) [Week1 End]
select cast(DATEADD(dd, -8-(DATEPART(dw, getdate())-2), getdate()) as date) [Week2 start]
select cast(DATEADD(dd, -14-(DATEPART(dw, getdate())-2), getdate()) as date) [Week2 END]
显示错误的输出,可以通过指出我出错的地方来帮助我,或者替代获取最近 6 周的开始和结束日期
【问题讨论】:
【参考方案1】:尝试将当前周开始/结束存储在变量中,然后使用DATEADD
计算前几周:
declare @weekStart date = cast(DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()) as date)
declare @weekEnd date = cast(DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate()) as date)
select @weekStart, @weekEnd
union all
select DATEADD(dd, -7, @weekStart), DATEADD(dd, -7, @weekEnd)
union all
select DATEADD(dd, -7 * 2, @weekStart), DATEADD(dd, -7 * 2, @weekEnd)
Demo here
【讨论】:
【参考方案2】:您也可以使用递归 CTE 解决此任务:
WITH cte
AS
(
SELECT cast(DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()) as date) [Week1 start], cast(DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate()) as date) [Week1 End]
UNION ALL
SELECT cast(DATEADD(dd, -7-(DATEPART(dw, [Week1 start])-1), [Week1 start]) as date) [Week1 start], cast(DATEADD(dd, -1-(DATEPART(dw, [Week1 End])-1), [Week1 End]) as date) [Week1 End]
FROM cte
WHERE [Week1 start]>'2021-01-10'
)
SELECT * FROM cte
【讨论】:
【参考方案3】:这是你要找的吗?
select cast(DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()) as date) [Week1 start]
select cast(DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate()) as date) [Week1 End]
select cast(DATEADD(dd, -8-(DATEPART(dw, getdate())-2), getdate()) as date) [Week2 start]
select cast(DATEADD(dd, -(DATEPART(dw, getdate())), getdate()) as date) [Week2 END]
select cast(DATEADD(dd, -15-(DATEPART(dw, getdate())-2), getdate()) as date) [Week3 start]
select cast(DATEADD(dd, -7-(DATEPART(dw, getdate())), getdate()) as date) [Week3 END]
【讨论】:
以上是关于如何在 MSSQL 中获取最近 6 周的开始日期和结束日期的主要内容,如果未能解决你的问题,请参考以下文章
mysql获取指定日期是当年第几周,指定日期所在周的开始和结束日期