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

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

    You can use the "brute force" approach with a twist:

    SELECT CASE
        WHEN Col1 <= Col2 AND Col1 <= Col3 THEN Col1
        WHEN                  Col2 <= Col3 THEN Col2
        ELSE                                    Col3
    END AS [Min Value] FROM [Your Table]
    

    When the first when condition fails it guarantees that Col1 is not the smallest value therefore you can eliminate it from rest of the conditions. Likewise for subsequent conditions. For five columns your query becomes:

    SELECT CASE
        WHEN Col1 <= Col2 AND Col1 <= Col3 AND Col1 <= Col4 AND Col1 <= Col5 THEN Col1
        WHEN                  Col2 <= Col3 AND Col2 <= Col4 AND Col2 <= Col5 THEN Col2
        WHEN                                   Col3 <= Col4 AND Col3 <= Col5 THEN Col3
        WHEN                                                    Col4 <= Col5 THEN Col4
        ELSE                                                                      Col5
    END AS [Min Value] FROM [Your Table]
    

    Note that if there is a tie between two or more columns then <= ensures that we exit the CASE statement as early as possible.

提交回复
热议问题