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

后端 未结 19 2119
余生分开走
余生分开走 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:47

    You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.

    Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
    From   YourTable T
           Inner Join (
             Select A.Id, Min(A.Col1) As TheMin
             From   (
                    Select Id, Col1
                    From   YourTable
    
                    Union All
    
                    Select Id, Col2
                    From   YourTable
    
                    Union All
    
                    Select Id, Col3
                    From   YourTable
                    ) As A
             Group By A.Id
           ) As A
           On T.Id = A.Id
    

提交回复
热议问题