本文介绍了是否可以设置T-SQL DATEDIFF函数的周开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用功能来过滤本周添加的记录:

I use DATEDIFF function to filter records added this week only:

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

,我注意到周日从星期几开始是什么假设。但在我的情况下,我宁愿在星期一设定一周的开始。是否可能在T-SQL中出现?

and I noticed what it's assumed what week starts on Sunday. But in my case I would prefer to set start of week on Monday. Is it possible somehow in T-SQL?

谢谢!

更新:

下面是一个示例,显示DATEDIFF不检查变量,所以我需要另一个解决方案。

Below is an example showing what DATEDIFF doesn't check @@DATEFIRST variable so I need another solution.

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。

26 Jul 2009 is Sunday, and I want DATEDIFF returns 0 in third column too.

推荐答案

是可能

SET DATEFIRST 1; -- Monday

from

出现datediff不尊重Datefirst,所以使它像这样运行它

It appears datediff doesn't respect the Datefirst, so make it do so run it like this

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

这篇关于是否可以设置T-SQL DATEDIFF函数的周开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 07:29