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

半腔热情 提交于 2019-11-27 20:25:25

Given this test data ...

SQL> select *
  2  from your_table
  3  /

NAME         M1         M2         M3         M4
---- ---------- ---------- ---------- ----------
A             1          2          3          4
B             6          3          4          5
C             1          5          2          1

SQL>

... a straightforward GREATEST() call will give the desired result:

SQL> select name
  2          , greatest(m1,m2,m3,m4)
  3  from your_table
  4  /

NAME GREATEST(M1,M2,M3,M4)
---- ---------------------
A                        4
B                        6
C                        5

SQL>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!