gpt4 book ai didi

tsql - 是否可以为 T-SQL DATEDIFF 函数设置一周的开始?

转载 作者:行者123 更新时间:2023-12-03 23:29:08 25 4
gpt4 key购买 nike

我用 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。

最佳答案

是的有可能

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

关于tsql - 是否可以为 T-SQL DATEDIFF 函数设置一周的开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1101892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com