SQL/T-SQL - how to get the MAX value from 1 of N columns?

15,004

Solution 1

With only three it's not so hard... This is definitely not extensible to an arbitrary number of datetime columns !

 Select Case When DT1 > DT2 And DT1 > DT3 Then DT1
             When DT2 > Dt3 Then Dt2 Else DT3 End
 From TableName

Solution 2

I think you need to normalize your database from

RecordID, Column1, Column2, Column3

to

RecordID, ColumnID, Value

Then you'll be able to find the max value in the three columns easily...

Solution 3

Perhaps a union?

select max(myDate)
from (
    select field_1 myDate from myTable where ...
    union all
    select field_2 myDate from myTable where ...
    union all
    select field_3 myDate from myTable where ...
) d

Of course, this hits the table three times for the same row. A CTE would probably solve that:

with myRow as (
    select field_1, field_2, field_3 from myTable where ...
)
select max(myDate)
from (
    select field_1 myDate from myRow
    union all
    select field_2 myDate from myRow
    union all
    select field_3 myDate from myRow
) d

Solution 4

SELECT 
(CASE WHEN field_1 > field_2 THEN 
    CASE WHEN field_1 > field_3 THEN field_1 ELSE field_3 END
ELSE
    CASE WHEN field_2 > field_3 THEN field_2 ELSE field_3 END
END) AS maximum_date
FROM table
Share:
15,004
pearcewg
Author by

pearcewg

Solution Architect, Software Executive. Senior Microsoft Development Professional and Leader. Certified Scrum Master (CSM).

Updated on June 27, 2022

Comments

  • pearcewg
    pearcewg almost 2 years

    In SQL/Transact SQL, I am trying to update a temp table to take the latest date from 3 different date columns (in that temp table), and put that MAX date into a "latest date" column.

    What is the best way to do this, using an update statement?