获取具有给定月份和年份的星期数,工作日的日期

时间:2019-06-30 12:02:30

标签: sql-server

我提供了月份和年份(例如,月份:7,年份:2019)

我需要获得最终的临时表,其中包含给定月份和年份的日期,星期数,工作日,如下所示。

DECLARE @TempWeekDates TABLE (ScheduleDate DATE, WeekNo INT, DayOfWeekUno INT, YearUno INT)

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试一下,它应该可以工作

DECLARE @TempWeekDates TABLE (ID INT IDENTITY(1,1), ScheduleDate DATE, WeekNo INT, DayOfWeekUno INT, MonthUno INT, YearUno INT)
DECLARE @Year INT = 2019, @Month INT = 7, @Count INT = 1
;WITH numbers
AS
(
Select 1 as value
UNION ALL
Select value + 1 from numbers
where value + 1 <= Day(EOMONTH(datefromparts(@Year,@Month,1)))
)
INSERT INTO @TempWeekDates (ScheduleDate, MonthUno, YearUno)
SELECT datefromparts(@Year,@Month,numbers.value) AS ScheduleDate, @Month, @Year FROM numbers
WHILE ((SELECT MAX(ID) FROM @TempWeekDates) >= @Count)
BEGIN
UPDATE @TempWeekDates SET DayOfWeekUno = DATEPART(dw,ScheduleDate), WeekNo= (DATEPART(WEEK, ScheduleDate)  -
DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,ScheduleDate), 0))+ 1) WHERE ID = @Count
SET @Count = @Count + 1
END
SELECT * FROM @TempWeekDates

答案 1 :(得分:0)

尝试以下操作:

DECLARE @MONTH INT = 7, @YEAR INT = 2019

DECLARE @StartDate datetime = DATEADD(mm,DATEDIFF(mm,0,DATEFROMPARTS(@YEAR, @MONTH, 1)),0) --get the first day of the month
DECLARE @EndDate   datetime = DATEADD(ms,- 3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@StartDate)+1,0))) --get the last day of the month

;WITH AllDates AS
     (SELECT @StartDate as theDate
      UNION ALL
      SELECT DATEADD(day, 1, theDate)
        FROM AllDates
       WHERE DATEADD(day, 1, theDate) <= @EndDate
     )
SELECT CONVERT(VARCHAR(10), theDate, 103) AS ScheduleDate, DATEPART(WEEK, theDate)- DATEPART(WEEK, @StartDate)+1 AS WeekNo, DATEPART(WEEKDAY, theDate) as DayOfWeekUno, @year YearUNo
  FROM AllDates
OPTION (MAXRECURSION 0)
;

答案 2 :(得分:0)

根据您的实际需求,您可能根本不需要临时表。例如,如果要创建表值函数,则可以直接返回递归CTE。像这样:

-- user input
DECLARE @yr INT = 2019;
DECLARE @m INT = 7;

-- derived values used by the query
DECLARE @dt DATE = DATEFROMPARTS(@yr, @m, 1);
DECLARE @week_nbr INT = DATEPART(WEEK, @dt);

-- beginning of actual query
WITH dates(d, wk) AS
(
    SELECT @dt, 1

    UNION ALL

    SELECT 
        DATEADD(DAY, 1, d),
        -- substracts this date's week number (for year) from the first date's 
        -- "year week number", and adds 1, to get the "month week number".
        DATEPART(WEEK, DATEADD(DAY, 1, d)) - @week_nbr + 1
    FROM dates 
    WHERE DATEPART(MONTH, DATEADD(DAY, 1, d)) = @m
)
SELECT
    d AS ScheduleDate,
    wk AS WeekNo,
    DATEPART(WEEKDAY, d) AS DayOfWeekUno,
    @yr AS YearUno
FROM dates