如何在一个月内找到第一,第二,第三和第四个星期六?

时间:2018-02-15 22:22:04

标签: tsql

如何找到本月的第一,第二,第三和第四个星期六?

例如:我想以这种格式结束......

  

块引用

YYYY,MM,第1周

  

块引用

YYYY,MM,第2周

  

块引用

谢谢,

3 个答案:

答案 0 :(得分:0)

这是一种方法,使用堆叠的cte创建一个内联计数表,另一个cte在其上生成月历。
请注意,您可以将第一行代码中的GETDATE()更改为您想要的任何日期(即使它在月中),代码将生成该月的所有星期六。

-- Get the current month's start date
DECLARE @MonthStart datetime = DATEADD(MONTH, (DATEDIFF(MONTH, 0, GETDATE())), 0)

;WITH lv0 AS (SELECT 0 g UNION ALL SELECT 0)
,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4
,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16
,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256
,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv3)

-- gets all the dates in the current month
,CurrentMonth AS (SELECT TOP (32) dateadd(day, n-1, @MonthStart) As TheDate
                  FROM Tally
                  WHERE MONTH(dateadd(day, n-1, @MonthStart)) = MONTH(@MonthStart)
                  ORDER BY n)

-- gets all the Saturday dates of the current month                    
SELECT TheDate, DATENAME(WEEKDAY, TheDate)
FROM CurrentMonth
WHERE DATEPART(WEEKDAY, TheDate) = 7 -- Depending on server settings!

如果您已有数字表,则可以使用它而不是堆叠的cte。如果你不知道什么是数字表以及为什么你应该有数字表,请阅读Jeff Moden的The "Numbers" or "Tally" Table: What it is and how it replaces a loop

答案 1 :(得分:0)

此解决方案不依赖于Datefirst设置。

declare @d datetime = getdate();

select
    dateadd(dd, n, firstSaturday)
from (
    select 
        firstSaturday = dateadd(day, 7-(@@datefirst+datepart(weekday, dateadd(day,-1, convert(char(6),@d,112)+'01')))%7, dateadd(day,-1, convert(char(6),@d,112)+'01'))
    ) t
    cross apply (values (0), (7), (14), (21)) q(n)

答案 2 :(得分:0)

你可以试试这个。

SET DATEFIRST 1

DECLARE @MonthId INT = 5
DECLARE @FirstDayOfTheMonth DATE = CONCAT(YEAR(GETDATE()), RIGHT(CONCAT('00', @MonthId),2), '01')
DECLARE @SaturdayId INT = 6 

SELECT 
    DATEADD(DAY, @SaturdayId + WK.ID - DATEPART(WEEKDAY, @FirstDayOfTheMonth), @FirstDayOfTheMonth)
FROM ( VALUES(0),(7),(14),(21),(28)) AS WK(ID)
WHERE 
    MONTH(DATEADD(DAY, @SaturdayId + WK.ID- DATEPART(WEEKDAY, @FirstDayOfTheMonth),@FirstDayOfTheMonth)) = @MonthId