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.
Whenever possible, use InLine functions as they suffer none of the performance issues generally associated with UDFs...
For usage guidelines, see Here
AFAIK, there is no built-in function to get the maximum of two values, but you can write your own easily as:
and call it as
CASE is IMHO your best option:
If one of the columns is nullable just need to enclose in
COALESCE
:You can throw this into a scalar function, which makes handling nulls a little easier. Obviously it isn't going to be any faster than the inline case statement.