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:
CASE is IMHO your best option:
SELECT ID,
CASE WHEN Date1 > Date2 THEN Date1
ELSE Date2
END AS MostRecentDate
FROM Table
If one of the columns is nullable just need to enclose in COALESCE:
.. COALESCE(Date1, '1/1/1973') > COALESCE(Date2, '1/1/1973')
I think the accepted answer is the simplest. However, I would watch for null values in the dates...
SELECT ID,
CASE WHEN ISNULL(Date1,'01-01-1753') > ISNULL(Date2,'01-01-1753') THEN Date1
ELSE Date2
END AS MostRecentDate
FROM Table
select ID,
case
when Date1 > Date2 then Date1
else Date2
end as MostRecentDate
from MyTable
select ID,(select max(d) from (select Date1 d uninon select Date2 d) as t) as MaxDate
from MyTable
AFAIK, there is no built-in function to get the maximum of two values, but you can write your own easily as:
CREATE FUNCTION dbo.GetMaximumDate(@date1 DATETIME, @date2 DATETIME)
RETURNS DATETIME
AS
BEGIN
IF (@date1 > @date2)
RETURN @date1
RETURN @date2
END
and call it as
SELECT Id, dbo.GetMaximumDate(Date1, Date2)
FROM tableName
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:
select id, max(dDate) MostRecentDate
from YourTable
unpivot (dDate for nDate in (Date1, Date2, Date3)) as u
group by id
Then you can order by dDate
, if that's helpful.