If I have a table that (among other columns) has two DATETIME columns, how would I select the most recent date from those two columns.
Example:
ID Date1 Date2
1 1/1/2008 2/1/2008
2 2/1/2008 1/1/2008
3 1/10/2008 1/10/2008
If I wanted my results to look like
ID MostRecentDate
1 2/1/2008
2 2/1/2008
3 1/10/2008
Is there a simple way of doing this that I am obviously overlooking? I know I can do subqueries and case statements or even write a function in sql server to handle it, but I had it in my head that there was a max-compare type function already built in that I am just forgetting about.
Why couldn't you use the GREATEST function?
I included a NVL to ensure that NULL was evaluated correctly, otherwise if either Date1 or Date2 is null, the Greatest returns NULL.
This thread has several solutions. If you had more than 2 dates to compare, "unpivot" might be preferable to writing a series of case statements. The following is blatantly stolen from Niikola:
Then you can
order by dDate
, if that's helpful.All other correct answers as already posted.
But if you are still really looking for MAX keyword then here is a way :
I think the accepted answer is the simplest. However, I would watch for null values in the dates...
Other than case statement, I don't believe so...