I want to compare data from the current week (1 through 52) to the data from two weeks prior. I need to make sure that when the new-year boundary is crossed, the comparison keeps working. I have a working predicate, like this:
WHERE ( DATEPART(ww,MA.DateOpen) + 1 ) % 52 = DATEPART(ww,@ImportDate) - 1
The above logic works, but it does not account for proximate years. In other words, unwanted data from week ‘X’ of all prior years will be included in the comparison. So the predicate must be expanded to account for years, which in turn requires handling the new year boundary: week 1 of 2012 should be compared against week 51 of 2011.
How can this be done without a verbose looking predicate?
update:
This question is complicated by the need for “week of year” to be treated as Tuesday through Tuesday. My current “correct” attempt is embodied in the [VerboseCheck] case below.
SET DATEFIRST 2
DECLARE @ImportDate date = '2011-1-4'
DECLARE @DateOpen date = '2010-12-20'
select @ImportDate,
YEAR(@DateOpen),
DATEPART(ww, @DateOpen),
YEAR(DATEADD(dd,-14,@ImportDate)),
DATEPART(ww,DATEADD(dd,-14,@ImportDate)),
CASE WHEN
YEAR(@DateOpen) + DATEPART(ww, @DateOpen) =
YEAR(DATEADD(dd,-14,@ImportDate)) + DATEPART(ww,DATEADD(dd,-14,@ImportDate))
THEN 1 ELSE 0 END [VerboseCheck],
CASE WHEN DATEDIFF (ww, @DateOpen, @ImportDate) =2
THEN 1 ELSE 0 END [SimpleCheck]
The [SimpleCheck] would be perfect, but it gives a different answer than [VerboseCheck]. If I advance @DateOpen one more day, then the two give the same answer. This suggests that both are not honoring the DATEFIRST evaluation in the same way.
Seems like DateDiff would be best used here. However as you noted DATEFIRST is indeed not respected.
So we just add Itzik Ben-Gan’s solution and we get