获取SQL Server中每n个月的第n个工作日日期

时间:2015-12-09 12:29:31

标签: sql sql-server-2008

我需要知道SQL Server中每个n个月的第n个工作日日期。例如,我需要从2015年1月1日到2015年12月30日的第2个星期一的所有日期。 这是工作日的日期。比如在每个第3个月的第一个星期一或第3个星期二之间。

2 个答案:

答案 0 :(得分:1)

前段时间我在这里回答了另一个问题: https://stackoverflow.com/a/32474751/5089204

简而言之:创建一个包含运行数字的表格( - > Tally Table)。在许多情况下,这样的桌子非常漂亮 - 无论如何都应该有这样的东西......它不需要太多,但它肯定会帮助你......

在此表格中,您可以使用简单的“SELECT'”获取所有需要的数据。也许您必须添加更多列并填充它们才能轻松获取数据。但这不应该是一个问题...

这将是结果(深入到2173年)

Number  CalendarDate    CalendarYear    CalendarMonth   CalendarDay CalendarWeek    CalendarYearDay CalendarWeekDay
0       1900-01-01      1900            1               1           1               1               1
1       1900-01-02      1900            1               2           1               2               2
2       1900-01-03      1900            1               3           1               3               3
3       1900-01-04      1900            1               4           1               4               4
4       1900-01-05      1900            1               5           1               5               5
5       1900-01-06      1900            1               6           1               6               6

为了提高性能,最好设置索引!

答案 1 :(得分:0)

这应该例如,返回所有第3个星期二:

;WITH AllDates AS (
    SELECT CAST('2015' + Mnth + Dy AS date) AS Dt
    FROM (
        SELECT '01' AS Mnth UNION SELECT '02' UNION SELECT '03' UNION SELECT '04' 
        UNION SELECT '05' UNION SELECT '06' UNION SELECT '07' UNION SELECT '08' 
        UNION SELECT '09' UNION SELECT '10' UNION SELECT '11' UNION SELECT '12'
    ) AS Mnths
    CROSS JOIN (
        SELECT '01' AS Dy UNION SELECT '02' UNION SELECT '03' UNION SELECT '04' 
        UNION SELECT '05' UNION SELECT '06' UNION SELECT '07' UNION SELECT '08' 
        UNION SELECT '09' UNION SELECT '10' UNION SELECT '11' UNION SELECT '12'
        UNION SELECT '13' UNION SELECT '14' UNION SELECT '15' UNION SELECT '16'
        UNION SELECT '17' UNION SELECT '18' UNION SELECT '19' UNION SELECT '20'
        UNION SELECT '21' UNION SELECT '22' UNION SELECT '23' UNION SELECT '24'
        UNION SELECT '25' UNION SELECT '26' UNION SELECT '27' UNION SELECT '28'
        UNION SELECT '29' UNION SELECT '30' UNION SELECT '31'
    ) AS Dys
    WHERE ISDATE('2015' + Mnth + Dy) = 1
), AllDatesWithInfo AS (
    SELECT Dt, DATENAME(weekday, Dt) AS WeekDay, ROW_NUMBER() OVER (PARTITION BY YEAR(Dt), MONTH(Dt), DATENAME(weekday, Dt) ORDER BY Dt) AS NumberOfThisWeekDayInMonth
    FROM AllDates
)
SELECT *
FROM AllDatesWithInfo
WHERE WeekDay = 'Tuesday'
AND NumberOfThisWeekDayInMonth = 3
ORDER BY Dt