SQL MAX of multiple columns?

后端 未结 22 1854
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 02:03

How do you return 1 value per row of the max of several columns:

TableName

[Number, Date1, Date2, Date3, Cost]

I n

22条回答
  •  后悔当初
    2020-11-22 02:29

    Well, you can use the CASE statement:

    SELECT
        CASE
            WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
            WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
            WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
            ELSE                                        Date1
        END AS MostRecentDate
    

    [For Microsoft SQL Server 2008 and above, you may consider Sven's simpler answer below.]

提交回复
热议问题