我使用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。
答案 0 :(得分:20)
是的可能
SET DATEFIRST 1; -- Monday
来自http://msdn.microsoft.com/en-us/library/ms181598.aspx
似乎dateiff不尊重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
从
被盗答案 1 :(得分:0)
我有另一个解决方案 这应该更容易理解,如果我错了,请纠正我
SET DATEFIRST 1
select DATEDIFF(week, 0, DATEADD(day, -@@DATEFIRST, '2018-04-15 00:00:00.000'))
我们从日期减去'-1',星期六到星期六(这是星期的第7天) 和Mondey(2)将在一周的第一天
答案 2 :(得分:0)
所以,如果我正确地得到了这个,
我们唯一需要做的就是从datediff
的两个日期中删除1天,如下所示:
DATEDIFF(week,dateadd(day,-1,cast(GETDATE() as date)),
dateadd(day,-1,cast([Date] as date))) as RollingWeek