oracle使用nullif解決除數(shù)為零的問題分析
oracle使用nullif解決除數(shù)為零
說一下nullif的語法

NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.
If both arguments are numeric data types, then Oracle Database determines the argument with the higher numeric precedence, implicitly converts the other argument to that data type, and returns that data type. If the arguments are not numeric, then they must be of the same data type, or Oracle returns an error.
The NULLIF function is logically equivalent to the following CASE expression:
CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END
如果兩個參數(shù)相等,返回null,否則返回第一個。
第一個參數(shù)不可指定為空。對于非數(shù)字類型參數(shù),數(shù)據(jù)類型必須一致。對于數(shù)值數(shù)據(jù)類型,會隱式的轉(zhuǎn)化為更高優(yōu)先級的數(shù)據(jù)類型。(這個理解可能有誤,我測試了int,integer,float。但是最終都轉(zhuǎn)化為number類型)。
一般來說
我們處理“除數(shù)為零”的問題會用到decode(當(dāng)然也可以用case,但是寫起來代碼更多些)。
比如:
dividend / decode(divisor, 0, null, divisor)
但是在除數(shù)divisor非常復(fù)雜的時候,就需要把這一大串代碼寫兩遍,或者是再套一層view。
無論是哪種,都是極其不利于維護的。
1 /
decode((sum(t.val) over(order by t.c) +
nvl(lead(val) over(partition by b order by c), 0)) /
sum(val) over(partition by b order by c),
0,
null,
(sum(t.val) over(order by t.c) +
nvl(lead(val) over(partition by b order by c), 0)) / sum(val)
over(partition by b order by c))對于這種復(fù)雜表達式的除數(shù),每回修改都要改兩遍,很容易出錯。
利用nullif,可以讓除數(shù)只寫一次。
因為 decode(divisor, 0, null, divisor) 與 nullif(divisor, 0) 是等效的。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
PLSQL無法連接64位Oracle數(shù)據(jù)庫/Database下拉框為空的完美解決方法
這篇文章主要介紹了PLSQL無法連接64位Oracle數(shù)據(jù)庫/Database下拉框為空的完美解決方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
Oracle數(shù)據(jù)庫升級到19C用戶登錄報錯問題解決辦法
oracle是一款非常流行的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),被廣泛應(yīng)用于各個領(lǐng)域,下面這篇文章主要給大家介紹了關(guān)于Oracle數(shù)據(jù)庫升級到19C用戶登錄報錯問題的解決辦法,需要的朋友可以參考下2024-08-08
使用MySQL語句來查詢Apache服務(wù)器日志的方法
這篇文章主要介紹了使用MySQL語句來查詢Apache服務(wù)器日志的方法,五個實例均基于Linux系統(tǒng)進行演示,需要的朋友可以參考下2015-06-06
Oracle使用pivot和unpivot函數(shù)實現(xiàn)行列轉(zhuǎn)換
項目開發(fā)過程中常常會涉及到oracle數(shù)據(jù)庫的一個數(shù)據(jù)操作,那就是行列的互轉(zhuǎn),本文為大家介紹了兩個可以實現(xiàn)這一操作的函數(shù)pivot和unpivot,感興趣的可以了解一下2023-06-06

