'Identify what column has the biggest date value and display it as a new column

I want know what column of a table is the bigger data.

I tried use case but my problem is when a column is null, in this situation the case condition is passed.

My code : (EDIT)

CASE WHEN data 1 >= data 2 AND data 1 >= data 3 AND
          data 1 >= data 4 THEN 'data 1'
     WHEN data 2 >= data 1 AND data 3 >= data 2 AND
          data 2 >= data 4 THEN 'data 2'
     WHEN data 3 > data 2 AND data 3 > data 1 AND
          data 3 > data 4 THEN 'data 3'
     WHEN data 4 > data 2 AND data 4 > data 1 AND
          data 4 > data 3 THEN 'data 4'
     END AS Bigger_Col_Is?

expected results:

  data 1  |  data 2  |  data 3  |  data 4  |Bigger_Col_Is?| Others Columns  
2021-01-31|   null   |2022-01-31|2022-04-20|    data 4    | others info  
2021-04-15|   null   |2022-01-31|   null   |    data 1    | others info 

(OBS: I'm using Microsoft SQL Server)



Solution 1:[1]

You can use cross apply

select data1, data2, data3, data4, t.n maxname
from mytable
cross apply (
    select top(1) n 
    from (
        values
          (data1,'data1'), (data2,'data2'), (data3,'data3'), (data4,'data4')
    ) t(d,n)
    order by d desc
) t

db<>fidle

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1