I have a table with three date fields. I need to return the latest (max) date of the three. I have a case statement that works fine unless a date is NULL at which point the function returns NULL. I need it to return the latest date of the three even if one or more is null. At any point either of the dates could be null but not all three.
The above returns:
I could write in error traps for Null values but the case gets crazy.
Can anybody come up with a more elegant solution?
Thanks,
Tim
Tim Roop
"If you can do something about it, why waste time getting upset? If you can't do anything about it, why bother getting upset on top of it? -Shantideva
Code:
Declare @Temp Table(EmpId VarChar(20), Date_1 smalldatetime, Date_2 smalldatetime, Date_3 smalldatetime)
Insert Into @Temp Values('01123DOE', '01/01/2001', '01/01/2002', '01/01/2003')
Insert Into @Temp Values('01123FOP', '01/01/2003', '01/01/2004', '01/01/2003')
Insert Into @Temp Values('01123JIM', '01/01/2000', '01/01/2002', '01/01/2000')
Insert Into @Temp Values('01123ACB', '01/01/2001', '01/01/2002', null)
Insert Into @Temp Values('01123FFF', '01/01/2001', '01/01/2002', '01/01/2003')
select EmpId, date_1, Date_2, Date_3,
case
when (date_1 >= date_2) AND (date_1 >= Date_3) then Date_1
when (date_2 >= date_1) AND (date_2 >= Date_3) then Date_2
when (date_3 >= date_1) AND (date_3 >= Date_2) then Date_3
end as MAX from @Temp
The above returns:
Code:
EmpID Date_1 Date_2 Date_3 Max
01123DOE 2001-01-01 2002-01-01 2003-01-01 2003-01-01
01123FOP 2003-01-01 2004-01-01 2003-01-01 2004-01-01
01123JIM 2000-01-01 2002-01-01 2000-01-01 2002-01-01
01123ACB 2001-01-01 2002-01-01 NULL NULL
01123FFF 2001-01-01 2002-01-01 2003-01-01 2003-01-01
I could write in error traps for Null values but the case gets crazy.
Can anybody come up with a more elegant solution?
Thanks,
Tim
Tim Roop
"If you can do something about it, why waste time getting upset? If you can't do anything about it, why bother getting upset on top of it? -Shantideva