SQL Server:获取ISO周的日期

问题描述 投票:0回答:3

花了一半时间试图弄清楚这个。

我希望根据他们的ISO周获得两个日期的datediff

这是我的代码:

SET DATEFIRST 1 ;   

DECLARE @A date, @B date;

SET @A = '20180829'; -- August 29th
SET @B = '20180902'; -- September 2nd

SELECT DATEDIFF(WW, @A, @B )

如果你检查:http://whatweekisit.org/(第35周,2018年)你可以看到它运行在8月27日到9月2日。

上面的代码将返回一个DateDiff = 1,该值应为0.尝试在ISO周上运行DateDiff只会返回以下错误:

date函数datediff不支持datepart iso_week

我已经尝试从日期中取出一周的dateparts,但是在比较不同年份的日期时我遇到了问题。

有没有解决的办法?

sql-server tsql date datediff date-difference
3个回答
2
投票

因此,经过一些阅读,没有一种本地的方式来做到这一点。但这是一个解决方法:

DECLARE @A DATE = '20180829' -- August 29th
DECLARE @B DATE = '20180902' -- September 2nd

--We need to back each date up to the first day of its week.
DECLARE @A_FIRSTWEEKDAY DATE = DATEADD(DAY, -(DATEPART(WEEKDAY, @A) - 1), @A)
DECLARE @B_FIRSTWEEKDAY DATE = DATEADD(DAY, -(DATEPART(WEEKDAY, @B) - 1), @B)

/*The WEEKDAY part counts Sunday as day 1. If the original date was
a Sunday, it backed up zero days and it still needs to back up six
days. If it was any other day, it backed all the way up to Sunday
and now it needs to move forward one day.*/
IF DATEPART(WEEKDAY, @A) = 1
     BEGIN SET @A_FIRSTWEEKDAY = DATEADD(DAY, -6, @A_FIRSTWEEKDAY) END
ELSE BEGIN SET @A_FIRSTWEEKDAY = DATEADD(DAY,  1, @A_FIRSTWEEKDAY) END
IF DATEPART(WEEKDAY, @B) = 1 
     BEGIN SET @B_FIRSTWEEKDAY = DATEADD(DAY, -6, @B_FIRSTWEEKDAY) END
ELSE BEGIN SET @B_FIRSTWEEKDAY = DATEADD(DAY,  1, @B_FIRSTWEEKDAY) END

--Now we can just difference the weeks.
SELECT DATEDIFF(DAY, @A_FIRSTWEEKDAY, @B_FIRSTWEEKDAY) / 7

1
投票

这是因为DATEDIFF总是使用星期日作为一周的第一天来确保函数以确定的方式运行:https://docs.microsoft.com/datediff-transact-sql

所以20180902(星期日)是下周的第一天。


0
投票
SELECT DATEDIFF(ww, DATEADD(dd,-1, @A ), DATEADD(dd,-1,@B)) 
--Seems to do the trick?

取自:Number of weeks and partial weeks between two days calculated wrong

虽然我不明白为什么链接中的其他帖子最后添加1。

© www.soinside.com 2019 - 2024. All rights reserved.