Oracle : select maximum value from different columns of the same row

前端 未结 2 1585
一向
一向 2020-12-05 10:01

The whole question is pretty much in the title. For each row of the table I\'d like to select the maximum of a subset of columns.

For example, from this table

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 10:23

    Use GREATEST but also handle possible NULL's

    SELECT name, GREATEST(NVL(m1,0), NVL(m2,0), NVL(m3,0), NVL(m4,0)) AS "Max"
    FROM yourtable
    

    Input:

    name m1 m2 m3 m4
    A    1  2  3  4
    B    6  3  4  5
    C    1  5  2  1
    

    Output:

    NAME Max
    A    4
    B    6
    C    5
    

    SQL Fiddle: http://sqlfiddle.com/#!4/ae268/7/0

    Input:

    name m1 m2   m3 m4
    A    1  2    3  null
    B    6  null 4  5
    C    1  5    2  1
    

    Output:

    NAME Max
    A    3
    B    6
    C    5
    

    SQL Fiddle: http://sqlfiddle.com/#!4/b1c46/1/0

提交回复
热议问题