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

In SQL / Transact SQL, I am trying to update a temporary table to get the latest date from three different date columns (in this temporary table) and put this MAX date in the "last date" column.

What is the best way to do this using update instructions?

+3
source share
6 answers

With just three, it's not that hard ... It's definitely not extensible for 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
+6
source

I think you need to normalize your database from

RecordID, Column1, Column2, Column3

to

RecordID, ColumnID, Value

Then you can easily find the maximum value in the three columns ...

+4

, ?

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

, . CTE, , :

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
+2
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
+1

3 'If', . 3- "" , () ...

.

0
0

All Articles