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

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

    If you use SQL 2005 you can do something neat like this:

    ;WITH    res
              AS ( SELECT   t.YourID ,
                            CAST(( SELECT   Col1 AS c01 ,
                                            Col2 AS c02 ,
                                            Col3 AS c03 ,
                                            Col4 AS c04 ,
                                            Col5 AS c05
                                   FROM     YourTable AS cols
                                   WHERE    YourID = t.YourID
                                 FOR
                                   XML AUTO ,
                                       ELEMENTS
                                 ) AS XML) AS colslist
                   FROM     YourTable AS t
                 )
        SELECT  YourID ,
                colslist.query('for $c in //cols return min(data($c/*))').value('.',
                                                'real') AS YourMin ,
                colslist.query('for $c in //cols return avg(data($c/*))').value('.',
                                                'real') AS YourAvg ,
                colslist.query('for $c in //cols return max(data($c/*))').value('.',
                                                'real') AS YourMax
        FROM    res
    

    This way you don't get lost in so many operators :)

    However, this could be slower than the other choice.

    It's your choice...

提交回复
热议问题