I try to get something in Oracle, if the commission
is greater than 0.2
I would like to get 'GOOD'
, otherwise 'BAD'
. And also if the commission is null
I want to get 0
. I know that is with NVL
, but something get wrong with syntax. Can you help me?
SELECT LAST_NAME,
SALARY,
DECODE(
NVL(COMMISSION_PCT),
COMMISSION_PCT < 0,2, 'BAD', COMMISSION_PCT > 0,2, 'GOOD'
) CommissionResult
FROM EMPLOYEES;
First of all, 0.2
should be written as 0.2
, not 0,2
. But most importantly, decode
is not suitable for this case.
In this case (and all other cases where you could use decode), you can use case
, which is more flexible and a more verbose so it is easier to read too.
SELECT LAST_NAME,SALARY,
CASE WHEN NVL(COMMISSION_PCT) < 0.2 THEN
'BAD'
WHEN COMMISSION_PCT > 0.2 THEN
'GOOD'
END as CommissionResult
FROM EMPLOYEES;
In your this case, you will get NULL
when the percentage is exactly 0.2. Maybe you just need an ELSE
clause instead:
SELECT LAST_NAME,SALARY,
CASE WHEN NVL(COMMISSION_PCT) < 0.2 THEN
'BAD'
ELSE
'GOOD'
END as CommissionResult
FROM EMPLOYEES;
DECODE(
NVL(COMMISSION_PCT),
COMMISSION_PCT < 0,2,'BAD',COMMISSION_PCT > 0,2,'GOOD'
)
Your query is syntactically incorrect.
NVL
syntax is incomplete For your requirement, you could use CASE expression which is verbose and easy to interpret.
Using CASE
For example, using the standard EMP table in SCOTT schema:
SQL> SELECT ename,
2 sal,
3 CASE
4 WHEN NVL(comm, 0) < 0.2
5 THEN 'BAD'
6 WHEN NVL(comm, 0) > 0.2
7 THEN 'GOOD'
8 END CommissionResult
9 FROM emp;
ENAME SAL COMM
---------- ---------- ----
SMITH 800 BAD
ALLEN 1600 GOOD
WARD 1250 GOOD
JONES 2975 BAD
MARTIN 1250 GOOD
BLAKE 2850 BAD
CLARK 2450 BAD
SCOTT 3000 BAD
KING 5000 BAD
TURNER 1500 BAD
ADAMS 1100 BAD
JAMES 950 BAD
FORD 3000 BAD
MILLER 1300 BAD
14 rows selected.
However, if you must use DECODE , then you need to use SIGN to have the same functionality.
Using DECODE
SQL> SELECT ename,
2 sal,
3 DECODE( SIGN(NVL(comm, 0) - 0.2), -1, 'BAD', +1, 'GOOD') CommissionResult
4 FROM emp;
ENAME SAL COMM
---------- ---------- ----
SMITH 800 BAD
ALLEN 1600 GOOD
WARD 1250 GOOD
JONES 2975 BAD
MARTIN 1250 GOOD
BLAKE 2850 BAD
CLARK 2450 BAD
SCOTT 3000 BAD
KING 5000 BAD
TURNER 1500 BAD
ADAMS 1100 BAD
JAMES 950 BAD
FORD 3000 BAD
MILLER 1300 BAD
14 rows selected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.