我必须创建 2 列:
startdate
和 enddate
,周日作为一周的第一个日期。
这是脚本
SELECT
MyDate,
DATEPART(WEEKDAY, CAST([MyDate] AS date)) AS WEEDAY,
DATEADD(D, -(DATEPART(WEEKDAY, CAST([MyDate] AS date))), CAST([MyDate] AS date)) StartDate,
DATEADD(D, (6 - DATEPART(WEEKDAY, CAST([MyDate] AS date))), CAST([MyDate] AS date)) EndDate
FROM
MyTable
WHERE
MyDate BETWEEN '2024-02-04' AND '2024-02-10'
ORDER BY
MyDate
但是我没有得到想要的结果。
周日 4 应该属于第 4-10 周。
我尝试更改
@@datefirst
,但得到了相同的结果。
你能帮忙吗?
谢谢你
对于
StartDate
,使用工作日的模 7 更简单,对于 EndDate
,只需在 StartDate
上添加六天即可:
SELECT
MyDate,
DATEPART(WEEKDAY, cast([MyDate] as date)) AS WEEDAY,
DATEADD(D, -(DATEPART(WEEKDAY, cast([MyDate] as date)) % 7), cast([MyDate] as date)) StartDate,
DATEADD(D, 6, DATEADD(D, -(DATEPART(WEEKDAY, cast([MyDate] as date)) % 7), cast([MyDate] as date))) EndDate
FROM MyTable
WHERE MyDate BETWEEN '2024-02-04' AND '2024-02-10'
ORDER BY MyDate