SQL MAX of multiple columns?

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

    There are 3 more methods where UNPIVOT (1) is the fastest by far, followed by Simulated Unpivot (3) which is much slower than (1) but still faster than (2)

    CREATE TABLE dates
        (
          number INT PRIMARY KEY ,
          date1 DATETIME ,
          date2 DATETIME ,
          date3 DATETIME ,
          cost INT
        )
    
    INSERT  INTO dates
    VALUES  ( 1, '1/1/2008', '2/4/2008', '3/1/2008', 10 )
    INSERT  INTO dates
    VALUES  ( 2, '1/2/2008', '2/3/2008', '3/3/2008', 20 )
    INSERT  INTO dates
    VALUES  ( 3, '1/3/2008', '2/2/2008', '3/2/2008', 30 )
    INSERT  INTO dates
    VALUES  ( 4, '1/4/2008', '2/1/2008', '3/4/2008', 40 )
    GO
    

    Solution 1 (UNPIVOT)

    SELECT  number ,
            MAX(dDate) maxDate ,
            cost
    FROM    dates UNPIVOT ( dDate FOR nDate IN ( Date1, Date2,
                                                Date3 ) ) as u
    GROUP BY number ,
            cost 
    GO
    

    Solution 2 (Sub query per row)

    SELECT  number ,
            ( SELECT    MAX(dDate) maxDate
              FROM      ( SELECT    d.date1 AS dDate
                          UNION
                          SELECT    d.date2
                          UNION
                          SELECT    d.date3
                        ) a
            ) MaxDate ,
            Cost
    FROM    dates d
    GO
    

    Solution 3 (Simulated UNPIVOT)

    ;WITH    maxD
              AS ( SELECT   number ,
                            MAX(CASE rn
                                  WHEN 1 THEN Date1
                                  WHEN 2 THEN date2
                                  ELSE date3
                                END) AS maxDate
                   FROM     dates a
                            CROSS JOIN ( SELECT 1 AS rn
                                         UNION
                                         SELECT 2
                                         UNION
                                         SELECT 3
                                       ) b
                   GROUP BY Number
                 )
        SELECT  dates.number ,
                maxD.maxDate ,
                dates.cost
        FROM    dates
                INNER JOIN MaxD ON dates.number = maxD.number
    GO
    
    DROP TABLE dates
    GO
    

提交回复
热议问题