SQL MAX of multiple columns?

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

    Unfortunately Lasse's answer, though seemingly obvious, has a crucial flaw. It cannot handle NULL values. Any single NULL value results in Date1 being returned. Unfortunately any attempt to fix that problem tends to get extremely messy and doesn't scale to 4 or more values very nicely.

    databyss's first answer looked (and is) good. However, it wasn't clear whether the answer would easily extrapolate to 3 values from a multi-table join instead of the simpler 3 values from a single table. I wanted to avoid turning such a query into a sub-query just to get the max of 3 columns, also I was pretty sure databyss's excellent idea could be cleaned up a bit.

    So without further ado, here's my solution (derived from databyss's idea).
    It uses cross-joins selecting constants to simulate the effect of a multi-table join. The important thing to note is that all the necessary aliases carry through correctly (which is not always the case) and this keeps the pattern quite simple and fairly scalable through additional columns.

    DECLARE @v1 INT ,
            @v2 INT ,
            @v3 INT
    --SET @v1 = 1 --Comment out SET statements to experiment with 
                  --various combinations of NULL values
    SET @v2 = 2
    SET @v3 = 3
    
    SELECT  ( SELECT    MAX(Vals)
              FROM      ( SELECT    v1 AS Vals
                          UNION
                          SELECT    v2
                          UNION
                          SELECT    v3
                        ) tmp
              WHERE     Vals IS NOT NULL -- This eliminates NULL warning
    
            ) AS MaxVal
    FROM    ( SELECT    @v1 AS v1
            ) t1
            CROSS JOIN ( SELECT @v2 AS v2
                       ) t2
            CROSS JOIN ( SELECT @v3 AS v3
                       ) t3
    

提交回复
热议问题