What's the best way to select the minimum value from several columns?

后端 未结 19 2116
余生分开走
余生分开走 2020-11-27 02:47

Given the following table in SQL Server 2005:

ID   Col1   Col2   Col3
--   ----   ----   ----
1       3     34     76  
2      32    976     24
3       7             


        
19条回答
  •  春和景丽
    2020-11-27 03:35

    If the columns were integers as in your example I would create a function:

    create function f_min_int(@a as int, @b as int) 
    returns int
    as
    begin
        return case when @a < @b then @a else coalesce(@b,@a) end
    end
    

    then when I need to use it I would do :

    select col1, col2, col3, dbo.f_min_int(dbo.f_min_int(col1,col2),col3)
    

    if you have 5 colums then the above becomes

    select col1, col2, col3, col4, col5,
    dbo.f_min_int(dbo.f_min_int(dbo.f_min_int(dbo.f_min_int(col1,col2),col3),col4),col5)
    

提交回复
热议问题