Question

I can calculate future pay dates with the following, knowing that 1/3/2013 was a pay day, and that we are paid every two weeks. This code tells me that 12/20/2013 was a payday. That's accurate.

declare @StartDate datetime = '1/4/13'
declare @FromDate datetime = '12/15/' + cast(year(getdate()) - 1 as char(4))

select dateadd(day, 14*cast(datediff(day, @StartDate, @FromDate) / 14 + 1 as int), @StartDate)

What I need to do, is calculate the last payday of the year. If I set @FromDate to 12/15/2013, this works, but I don't believe I can rely on that in cases where December is a three check month. My preference is to set the FromDate to 12/01/YYYY and get the last payday of that year, but I cannot seem to wrap my mind around how to pull that off.

How do I need to alter this to get the last Payday (always a Friday) of the year?

Thanks in advance for the forthcoming suggestions.

Était-ce utile?

La solution

considering that it will always be either the last friday or the penultimate friday of the year, this should work:

declare @startdate datetime='20140110'
declare @lastdayofyear datetime='20141231'
select 
case datediff(WEEK,@startdate,dateadd(day,6-datepart(w,@lastdayofyear)-7,@lastdayofyear)) % 2
when 0 then
dateadd(day,datepart(w,6-@lastdayofyear)-7,@lastdayofyear)
else
dateadd(day,datepart(w,6-@lastdayofyear)-14,@lastdayofyear)
end

Autres conseils

This could be done fairly easily with a date dimension table. Using the example in the link, a query would look like this:

SELECT TOP 1 [Date] FROM DimDate 
WHERE DATEPART(dw, [Date]) = 6 --is Friday
    AND DATEPART(wk, [Date]) % 2 = 0--Is an even week
    AND YEAR([Date]) = YEAR(getdate())--Current year
ORDER BY [Date] DESC

There are 52 weeks in a year. Assuming one is paid bi-weekly as seems to be the case here, you can add 50 weeks to the start date to get the last date in the year.

declare @StartDate datetime = '1/4/13'
declare @FromDate datetime = '12/15/' + cast(year(getdate()) - 1 as char(4))

select dateadd(week, 50, @StartDate)

set @StartDate = '1/3/14'

select dateadd(week, 50, @StartDate)

First result is 12/20/2013. Second result is 12/19/2014.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top