2009-12-15 53 views
2

以下問題,我想在Oracle中創建一個視圖,以計算「利用率百分比」。Oracle查看問題與選擇和divison零

AS SELECT 
    sw.SWITCH_ID, 
    sw.ASSET_ID, 
    sw.SYSTEMNAME, 
    sw.MAX_INSTALLABLE_PORTS, 
    sw.INSTALLED_PORTS, 
    sw.USED_PORTS, 
    (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 AS UTIL_INSTALLED_PORTS, 
    sw.RES_INFRASTRUCTURE_PORTS, 
    sw.USED_INFRASTRUCTURE_PORTS, 
    sw.FREE_INFRASTRUCTURE_PORTS, 
    (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 AS UTIL_INFRASTRUCTURE_PORTS, 
    sw.RESERVED_DEVICE_PORTS, 
    sw.USED_DEVICE_PORTS, 
    sw.FREE_DEVICE_PORTS, 
    (sw.FREE_DEVICE_PORTS/sw.RESERVED_DEVICE_PORTS)*100 AS UTIL_DEVICE_PORTS, 
    sw.RUN_DATE 

問題:有時sw.INSTALLED_PORTS或sw.MAX_INSTALLABLE_PORTS可以爲NULL(同爲其他UTIL行)..

有沒有什麼好的辦法做這樣的事情:

if (sw.INSTALLED_PORTS or sw.MAX_INSTALLABLE_PORTS == null) 
     UTIL_INSTALLABLE_PORTS = null 
else (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 AS UTIL_INSTALLABLE_PORTS, 

回答

4

NULL的分割與零分割不同(因爲您引用標題中的問題)。

select 1/null from dual = NULL
​​= NULL

所以,你會自動得到你想要的東西(sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100

我認爲,問題是當sw.MAX_INSTALLABLE_PORTS爲零。在這種情況下,你可以使用以下命令:

case 
    when sw.MAX_INSTALLABLE_PORTS = 0 then null 
    else (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 
end 
+0

你太棒了!感謝 – opHASnoNAME 2009-12-15 13:50:54

4
CASE 
    WHEN sw.INSTALLED_PORTS IS NULL OR sw.MAX_INSTALLABLE_PORTS IS NULL THEN NULL 
    ELSE (sw.INSTALLED_PORTS/sw.MAX_INSTALLABLE_PORTS)*100 
END UTIL_INFRASTRUCTURE_PORTS 
2

您可以使用COALESCE()從其參數返回第一個非空,如:

(COALESCE(sw.INSTALLED_PORTS, 0)/COALESCE(sw.MAX_INSTALLABLE_PORTS,1))*100 
AS UTIL_DEVICE_PORTS 

請注意,我使用1作爲分母中的coalesce默認值,您不需要DIVIDE/0。

+0

我不認爲這是一回事。如果sw.INSTALLED_PORTS或sw.MAX_INSTALLABLE_PORTS爲空,他希望UTIL_INSTALLABLE_PORTS爲空。您的代碼將返回0爲下面的情況,但根據OP的代碼結果應該是NULL: SELECT(COALESCE(NULL,0)/ COALESCE(NULL,1))* 100 AS UTIL_DEVICE_PORTS FROM dual – dcp 2009-12-15 13:27:28

+0

公平的評論, – 2009-12-15 13:28:43

5

或短一點:

sw.INSTALLED_PORTS/NULLIF(sw.MAX_INSTALLABLE_PORTS,0) 

問候, 羅布。

+0

對'NULLIF'的+1 – pilcrow 2009-12-15 17:39:04