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

前端 未结 2 1574
孤独总比滥情好
孤独总比滥情好 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: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
    

提交回复
热议问题