T-SQL how to get date range for 2 week pay period

前端 未结 2 1571
孤独总比滥情好
孤独总比滥情好 2021-01-21 08:55

I have following seed input data:

  1. Payperiod start: Dec 3rd
  2. Payperiod end: Dec 16

Thats just example how company payroll goes.

Now,

相关标签:
2条回答
  • 2021-01-21 09:50

    Would the following not work?

    DECLARE @StartDate DATETIME
    SELECT @StartDate = '2016-05-01 00:00:00.000'
    DECLARE @EndDate DATETIME
    SELECT @EndDate = '2017-04-01 00:00:00.000'
    
    DECLARE @Dates TABLE(StartDate DATETIME, EndDate DATETIME)
    
    WHILE @StartDate <= @EndDate
    BEGIN
    INSERT INTO @Dates (StartDate, EndDate)
    SELECT @StartDate - 13, @StartDate WHERE DATEPART(WEEK, @StartDate) % 2 = 1 AND DATEPART(WEEKDAY, @StartDate) = 7
    
    SET @StartDate = @StartDate + 1 
    END
    
    -- Check the dates here... should be every 2 weeks
    SELECT * FROM @Dates
    
    0 讨论(0)
  • 2021-01-21 09:56

    You need some modulo operations and DATEDIFF.

    declare @periodStart datetime
    declare @periodEnd datetime
    
    set @periodStart = CAST('2011-12-03' as datetime)
    set @periodEnd = CAST('2011-12-16' as datetime)
    
    declare @anyDate datetime
    set @anyDate = CAST('2011-12-30' as datetime)
    
    declare @periodLength int
    set @periodLength = DATEDIFF(day, @periodStart, @periodEnd) + 1
    
    
    declare @daysFromFirstPeriod int
    set @daysFromFirstPeriod = DATEDIFF(day, @periodStart, @anyDate)
    declare @daysIntoPeriod int
    set @daysIntoPeriod = @daysFromFirstPeriod % @periodLength
    
    select @periodLength as periodLength, @daysFromFirstPeriod as daysFromFirstPeriod, @daysIntoPeriod as daysIntoPeriod
    select DATEADD(day, -@daysIntoPeriod, @anyDate) as currentPeriodStart, DATEADD(day, @periodLength -@daysIntoPeriod, @anyDate) as currentPeriodEnd
    

    Gives output

    periodLength    daysFromFirstPeriod daysIntoPeriod
    14              27                  13
    

    and

    currentPeriodStart        currentPeriodEnd
    2011-12-17 00:00:00.000   2011-12-31 00:00:00.000
    
    0 讨论(0)
提交回复
热议问题