views:

103

answers:

2

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

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

the result would be

name max
A      4
B      6
C      5

The query must be compatible oracle 8i.

Thanks.

A: 

Take a look at this solution to a similar problem

Mark Baker
+9  A: 

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>
APC
+1 Wow! I've been working with Oracle since 7.3.4 was new, and never even knew that function existed.
Mark Baker
@MarkBaker - it was introduced in Oracle8.0.
APC
Nah, it's older than that. It's in the Oracle 7.3 manual
Dave Costa
@DaveCosta - It wasn't in the 7.0 manual, so shall we split the difference?
APC
That's exactly what I was looking for, thanks.
gregseth
Just a warning that, if any of the columns is NULL, greatest will always return NULL
Gary