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:
Why couldn't you use the GREATEST function?
select id, date1, date2, GREATEST( nvl(date1,date2) , nvl(date2, date1) )
from table1;
I included a NVL to ensure that NULL was evaluated correctly, otherwise if either Date1 or Date2 is null, the Greatest returns NULL.
ID Date1 Date2 MostRecentDate
1 1/1/2008 2/1/2008 2/1/2008
2 2/1/2008 1/1/2008 2/1/2008
3 1/10/2008 1/10/2008 1/10/2008
4 -null- 2/10/2008 2/10/2008
5 2/10/2008 -null- 2/10/2008
select max(d) ChangeDate
from (values(@d), (@d2)) as t(d)
From SQL Server 2012 it's possible to use the shortcut IIF to CASE
expression though the latter is SQL Standard:
SELECT ID,
IIF(DateColA > DateColB, DateColA, DateColB) AS MostRecentDate
FROM theTable
All other correct answers as already posted.
But if you are still really looking for MAX keyword then here is a way :
select ID , MAX(dt) from
( select Id , Date1 as dt from table1
union
select ID , Date2 from table2
) d
group by d.Id
Other than case statement, I don't believe so...
Select Case When DateColA > DateColB Then DateColA
Else DateColB End MostRecent
From Table ...
Whenever possible, use InLine functions as they suffer none of the performance issues generally associated with UDFs...
Create FUNCTION MaximumDate
(
@DateTime1 DateTime,
@DateTime2 DateTime
)
RETURNS TABLE
AS
RETURN
(
Select Case When @DateTime1 > @DateTime2 Then @DateTime1
Else @DateTime2 End MaxDate
)
GO
For usage guidelines, see Here