14

我只使用DATEDIFF函数过滤本周添加的记录:

DATEDIFF(week, DateCreated, GETDATE()) = 0

我注意到它假设星期天从星期天开始。但就我而言,我更愿意将一周的开始时间设置在星期一。在 T-SQL 中是否有可能?

谢谢!


更新:

下面是一个显示 DATEDIFF 不检查@@DATEFIRST变量的示例,因此我需要另一个解决方案。

SET DATEFIRST 1;

SELECT 
    DateCreated, 
    DATEDIFF(week, DateCreated, CAST('20090725' AS DATETIME)) AS D25, 
    DATEDIFF(week, DateCreated, CAST('20090726' AS DATETIME)) AS D26
FROM
(
    SELECT CAST('20090724' AS DATETIME) AS DateCreated
    UNION 
    SELECT CAST('20090725' AS DATETIME) AS DateCreated
) AS T

输出:

DateCreated             D25         D26
----------------------- ----------- -----------
2009-07-24 00:00:00.000 0           1
2009-07-25 00:00:00.000 0           1

(2 row(s) affected)

2009 年 7 月 26 日是星期日,我希望 DATEDIFF 在第三列也返回 0。

4

3 回答 3

22

是的,有可能

SET DATEFIRST 1; -- Monday

来自http://msdn.microsoft.com/en-us/library/ms181598.aspx

看来 datediff 不尊重 Datefirst,所以让它像这样运行它

create table #testDates (id int identity(1,1), dateAdded datetime)
insert into #testDates values ('2009-07-09 15:41:39.510') -- thu
insert into #testDates values ('2009-07-06 15:41:39.510') -- mon
insert into #testDates values ('2009-07-05 15:41:39.510') -- sun
insert into #testDates values ('2009-07-04 15:41:39.510') -- sat

SET DATEFIRST 7 -- Sunday (Default
select * from #testdates where datediff(ww, DATEADD(dd,-@@datefirst,dateadded), DATEADD(dd,-@@datefirst,getdate())) = 0
SET DATEFIRST 1 -- Monday
select * from #testdates where datediff(ww, DATEADD(dd,-@@datefirst,dateadded), DATEADD(dd,-@@datefirst,getdate())) = 0

偷来的

http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/8cc3493a-7ae5-4759-ab2a-e7683165320b

于 2009-07-09T04:57:35.467 回答
2

我有另一个解决方案。这应该更容易理解,如果我错了,请纠正我

SET DATEFIRST 1
select DATEDIFF(week, 0, DATEADD(day, -@@DATEFIRST, '2018-04-15 00:00:00.000'))

我们从日期中减去“-1”,星期日将变为星期六(这是一周的第 7 天),Mondфy(2) 将成为一周的第一天

于 2018-04-13T18:18:42.867 回答
0

因此,如果我正确理解了这一点,我们唯一需要做的就是从datediff以下两个日期中删除 1 天:

DATEDIFF(week,dateadd(day,-1,cast(GETDATE() as date)),
dateadd(day,-1,cast([Date] as date))) as RollingWeek 
于 2020-10-09T14:25:13.953 回答