2016-04-15 82 views
-1

我正在Oracle Apex中創建一個數據庫,我基本上需要比較同一行中的兩個數字,以便我可以找到哪個數據最大。下面的示例表格;SQL-如何比較同一行中的兩個數字

enter image description here

使用上面的例子,我將如何在同一行比較數1和2號例如將第一行比較6與7,然後將第二行比較3與1。

+1

你怎麼想顯示比較的結果?你想從你的查詢中得到什麼輸出? –

+0

你應該能夠做的情況下(number1> number2),然後做一些事情只是開始... – cableload

+0

嗨亞歷克斯,我只是想顯示它在選擇查詢,它選擇最高的數字 – BiscuitCookie

回答

2

如果你的號碼的最小值(即它們都是正整數),那麼你可以這樣做:

甲骨文設置

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;