I am creating a database in Oracle Apex and I basically need to compare two numbers in the same row so that I can find which is the biggest. Example table below;
Using the example above, how would I compare Number 1 and Number 2 on the same row e.g. Compare 6 against 7 for the first row then compare 3 against 1 for the second row.
If there is a minimum value for your numbers (i.e. they are all positive integers) then you can do:
CREATE TABLE table_name ( ID, name, number1, number2, number3 ) AS SELECT 1, 'Jane', 6, 7, 1 FROM DUAL UNION ALL SELECT 2, 'John', 3, 1, NULL FROM DUAL UNION ALL SELECT 3, 'Jake', NULL, NULL, 5 FROM DUAL;
SELECT ID, NAME, GREATEST( NVL( NUMBER1, 0 ), NVL( NUMBER2, 0 ), NVL( NUMBER3, 0 ) ) AS biggest FROM table_name;
ID NAME BIGGEST ---------- ---- ---------- 1 Jane 7 2 John 3 3 Jake 5
If there is no minimum value then you can do:
SELECT ID, NAME, CASE WHEN NUMBER1 IS NULL AND NUMBER2 IS NULL AND NUMBER3 IS NULL THEN NULL WHEN NUMBER1 IS NULL AND NUMBER2 IS NULL THEN NUMBER3 WHEN NUMBER1 IS NULL AND NUMBER3 IS NULL THEN NUMBER2 WHEN NUMBER2 IS NULL AND NUMBER3 IS NULL THEN NUMBER1 WHEN NUMBER1 IS NULL THEN GREATEST( NUMBER2, NUMBER3 ) WHEN NUMBER2 IS NULL THEN GREATEST( NUMBER1, NUMBER3 ) WHEN NUMBER3 IS NULL THEN GREATEST( NUMBER1, NUMBER2 ) ELSE GREATEST( NUMBER1, NUMBER2, NUMBER3 ) END AS biggest FROM table_name;