SQL-如何比较同一行中的两个数字

时间:2016-04-15 18:10:37

标签: sql database oracle compare oracle-apex

我正在Oracle Apex中创建一个数据库,我基本上需要比较同一行中的两个数字,以便找到最大的数字。下面的示例表;

enter image description here

使用上面的例子,我如何比较同一行的数字1和数字2,例如比较6对7的第一行,然后将3与第二行的1进行比较。

1 个答案:

答案 0 :(得分:2)

如果您的数字有最小值(即它们都是正整数),那么您可以这样做:

Oracle安装程序

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 

如果没有最小值,那么你可以这样做:

查询2

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;