SQL MAX of multiple columns?

后端 未结 22 2150
伪装坚强ぢ
伪装坚强ぢ 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

    You could create a function where you pass the dates and then add the function to the select statement like below. select Number, dbo.fxMost_Recent_Date(Date1,Date2,Date3), Cost

    create FUNCTION  fxMost_Recent_Date 
    

    ( @Date1 smalldatetime, @Date2 smalldatetime, @Date3 smalldatetime ) RETURNS smalldatetime AS BEGIN DECLARE @Result smalldatetime

    declare @MostRecent smalldatetime
    
    set @MostRecent='1/1/1900'
    
    if @Date1>@MostRecent begin set @MostRecent=@Date1 end
    if @Date2>@MostRecent begin set @MostRecent=@Date2 end
    if @Date3>@MostRecent begin set @MostRecent=@Date3 end
    RETURN @MostRecent
    

    END

提交回复
热议问题