简体   繁体   English

如何找到最接近的FRI?

[英]How to find closest FRI?

In SQL Server 2008, given a date, how would I get a date corresponding to FRI of that week? 在SQL Server 2008中,给定日期,我如何获得对应于该周FRI的日期?

so for example:
6/6/2012 -> 6/8/2012
6/5/2012 -> 6/8/2012

Assuming you want 6/9/2012 to also return 6/8/2012 (same week), this would work. 假设您希望2012年6月9日还返回2012年6月8日(同一周),则可以使用。 It get's the day of week of the current date and adds the difference between that and Friday which is hardcoded to a value of 6. 它是当前日期的星期几,并将该日期与星期五之间的差值加硬编码为6。

SET DATEFIRST 7;    
declare @date date = '6/5/2012'

select dateadd(dd,6-datepart(dw,@date),@date) as Friday

If you want 6/9/2012 to return the next Friday, you just have to make a small modification: 如果您希望2012年6月9日返回下一个星期五,则只需做一些小修改:

SET DATEFIRST 7;
declare @date date = '6/9/2012'
set @date = dateadd(dd,1,@date) -- this adds a day to the date you inputted but doesn't matter since the function will always return to you a Friday
-- Sunday resets the week with datepart so adding a day to Saturday resets the week resulting in the next week being returned.

select dateadd(dd,6-datepart(dw,@date),@date) as Friday

Here's a function I created that seems to work. 这是我创建的似乎起作用的功能。 It does not change DATEFIRST and will give you the next date for the DOW. 它不会更改DATEFIRST,并将为您提供DOW的下一个日期。 The function will return the date you passed in if it is on the DOW you are looking for. 该函数将返回您传递的日期(如果它在您要查找的DOW上)。

CREATE FUNCTION [dbo].[func_NextDate]
(
    @dt DATE,
    @dow INT -- Use the day-of-week as defined by SQL Server (1=Sun, 7=Sat)
)
RETURNS DATE
AS 
BEGIN

DECLARE @dtDiff INT = 7-((DATEPART(dw, @dt)+(7-@dow))%7)
IF @dtDiff = 7
    SET @dtDiff = 0 -- Return the date if it is on the dow requested

RETURN DATEADD(dd, @dtDiff, @dt)

END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM