首页 文章

SQL:获得第二个完整周的星期五

提问于
浏览
2

这是一个有趣的方程式 . 我正在寻找最简洁的方法来检索每个月的第二个完整周五 . 假设周从星期一开始 .

EXAMPLES

  • November 2017 将是 17th .

  • December 2017 将是 15th .

  • January 2018 将是 12th .

这些东西通常都很有趣,但我现在感觉不舒服 . 有什么建议?

3 回答

  • 1

    这可能一开始并不容易理解,但对于这个特定情况,规则很简单:

    weekday = 'Friday' (or whichever way to determine if this day is Friday)
    and day_of_month between 12 and 18
    

    如果星期一开始,这将有效 .

  • 0

    如果工作周在星期一开始,那么一个月的第二个完整工作周的星期五是

    SELECT DATEADD(day, (9 - DATEPART(weekday, @fdom)) % 7) + 11, @fdom)
           AS SecondWorkweekFriday;
    
    -- 1. start with the first day of the month (@fdom)
    -- 2. advance to the nearest Monday with modular arithmetic
    --    n.b.: by default DATEPART considers Monday to be ordinal
    --          week day #2, thus "7 - DATEPART() + 2" becomes
    --          "9 - DATEPART"
    -- 3. add eleven days to get to the second Friday thereafter
    

    @fdom是这个月的第一天 . 有很多方法可以在SQL中找到first day of the month .

  • 3

    我个人喜欢这样的日期表,但你也可以算出来:

    CASE WHEN datepart(weekday, '2017-12-01')<=5 THEN 7 ELSE 14 END + (7-datepart(weekday, '2017-12-01'))
    

    可能需要调整 5 ,但我认为这是正确的,因为 datepart(weekday 是基于星期日的,你是星期一(可能需要6才能正确抵消) .

    无论如何,这应该让你进入球场 .

相关问题