gpt4 book ai didi

datetime - 获取与 SQL Server 2012 中的最后一个星期四或星期五或星期一等对应的日期时间

转载 作者:行者123 更新时间:2023-12-01 23:45:07 25 4
gpt4 key购买 nike

我有一个特定的 DATETIME 值,我想获取给定日期之前的给定工作日“n”(其中 n 是从 1 到 7 的整数)的 DATETIME 值。

问题:给定 currentDate 的值和 lastWeekDay 的值,我将如何做到这一点?

例如,如果给定日期为 mm/dd/yyyy 格式的 06/15/2015,那么在 06/15/2015 之前的工作日 6 的日期是多少。在这个例子中,给定的日期是星期一,我们想要上星期五的日期(即工作日 =6)。

declare @currentDate datetime, @lastWeekDay int;
set @currentDate = getdate();
set @lastWeekDay = 6;--this could be any value from 1 thru to 7
select @currentDate as CurrentDate, '' as LastWeekDayDate --i need to get this date

更新 1

除了 Anon 的出色回答之外,我还找到了另一种方法,如下所示。

DECLARE @currentWeekDay INT;
SET @currentWeekDay = DATEPART(WEEKDAY, @currentDate);

--Case 1: when current date week day > lastWeekDay then subtract
-- the difference between the two weekdays
--Case 2: when current date week day <= lastWeekDay then go back 7 days from
-- current date, and then add (lastWeekDay - currentWeekDay)

SELECT
@currentDate AS CurrentDate,
CASE
WHEN @currentWeekDay > @lastWeekDay THEN DATEADD(DAY, -1 * ABS(CAST(@lastWeekDay AS INT) - CAST(@currentWeekDay AS INT)), @currentDate)
ELSE DATEADD(DAY, @lastWeekDay - DATEPART(WEEKDAY, DATEADD(DAY, -7, @currentDate)), DATEADD(DAY, -7, @currentDate))
END AS LastWeekDayDate;

最佳答案

计算自固定日期以来经过了多少天,以 7 为模,然后从输入日期中减去该天数。魔数(Magic Number)“5”是因为日期零 (1900-01-01) 是星期一。将其向前移动 5 天会使 @lastWeekDay 范围 [1..7] 映射到工作日范围 [Sunday..Saturday]。

SELECT DATEADD(day,-DATEDIFF(day,5+@lastWeekDay,@currentDate)%7,@currentDate)

由于 SET DATEFIRST,我避免使用 DATEPART(weekday,[...]) 函数

关于datetime - 获取与 SQL Server 2012 中的最后一个星期四或星期五或星期一等对应的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704514/

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