I’ve got a data set with dates and want to check if the date order is correct.
RecordID Date1 Date2 Date3 Date4
1 2011-05-10 2011-08-16 NULL 2011-11-22
2 NULL 2012-02-03 2012-02-27 2012-03-05
3 2011-05-30 2011-05-11 2011-08-17 2011-09-15
4 2011-05-30 NULL NULL NULL
In all cases when dates are provided, this should hold: Date1 < Date2 < Date3 < Date4. When the record contains NULL values for certain dates, the check should be made between the dates that are not NULL. So this is the result I want:
RecordID Date1 Date2 Date3 Date4 CheckDates
1 2011-05-10 2011-08-16 NULL 2011-11-22 correct
2 NULL 2012-02-03 2012-02-27 2012-03-05 correct
3 2011-05-30 2011-05-11 2011-08-17 2011-09-15 incorrect
4 2011-05-30 NULL NULL NULL correct
I’ve written an extensive CASE statement for this, but there must be a more elegant solution:
CASE
WHEN Date1 IS NULL AND Date2 IS NULL AND Date3 IS NULL AND Date4 IS NULL THEN 'correct'
WHEN Date1 IS NULL AND Date2 IS NULL AND Date3 IS NULL AND Date4 IS NOT NULL THEN 'correct'
WHEN Date1 IS NULL AND Date2 IS NULL AND Date3 IS NOT NULL AND Date4 IS NULL THEN 'correct'
WHEN Date1 IS NULL AND Date2 IS NULL AND Date3 IS NOT NULL AND Date4 IS NOT NULL AND Date3 < Date4 THEN 'correct'
...
ELSE 'incorrect'
END
Any ideas?
EDIT:
I am looking for a solution that allows for more ‘Date’ columns than the three columns in the first example I gave above (I’ve got four in my real-world problem, and changed it to three to simplify the problem, but seems I’ve lost a significant characteristic with this simplification). Updated the example for four columns.
You can use
ISNULLandCOALESCEto skip over the null values. If the date is missing, just replace it with a date that will always pass the check:This assumes your “real” dates would never go outside the rage 1900 – 3000 of course; there’s the next millenium bug just waiting to happen 😉
EDIT: Edited to handle four fields