質問

i have the following data but in query i got the zero problem in division by zero. so i want the output as given below in two forms.

drop table t;

create table t (id number(9), val1 number(9), val2 number(9));
insert into t values (1,23,2);
insert into t values (2,0,4);
insert into t values (3,7,4);
insert into t values (4,0,3);
insert into t values (5,4,6);

select sqrt(val2*val1)/val1 from t ;

SQL> / ERROR: ORA-01476: divisor is equal to zero

expected reults

in two forms first query like this

        ID SQRT(VAL2*VAL1)/VAL1
---------- --------------------
         1           .294883912
         2                    0
         3           .755928946
         4                    0
         5           1.22474487

second query like this

       ID SQRT(VAL2*VAL1)/VAL1
---------- --------------------
         1           .294883912
         3           .755928946
         5           1.22474487
役に立ちましたか?

解決

You can use

select sqrt(val2*val1)/val1 from t where val1 != 0;

That will avoid the rows where val1 is 0 and so will not cause the "divide by 0" error. This should give you the second format.

For the first format where you want to show the 0 in the output you can use a case statement in the where clause.

select id, 
case 
    when val1 = 0 then 0
    when val1 != 0 then sqrt(val2*val1)/val1
end
from t 

他のヒント

Consider using a DECODE and NVL. In DECODE (if/then/else) specify the logic with or without zero. If you want to use some other value instead, use NVL.

Decode example:

SELECT DECODE(val1, 0, NULL, sqrt(val2*val1)/val1)  from t;

Hope this helps.

In your Data insert into t values (2,0,4); val1 is 0 so it will not allow this to Divide with 0. so either you need to check first weather val1 is 0 or not then perform this.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top