测试table的记录如下:
SQL> select * from testnvl;
ID FAB MONTH
---------- ---------- --------
2112 S1 2010-06
234 S2 2010-06
0 S3 2010-06
需要根据FAB和MONTH的值从表里查ID,如果有值的显示原值,如果没有或为0的显示成1。
SQL如下:
select decode(id,null,1,0,1,id) from testnvl where......
测试结果:
SQL> select decode(id,null,1,0,1,id) from testnvl where fab='S1' and month='2010-06';
DECODE(ID,NULL,1,0,1,ID)
------------------------
2112
SQL> select decode(id,null,1,0,1,id) from testnvl where fab='S3' and month='2010-06';
DECODE(ID,NULL,1,0,1,ID)
------------------------
1
SQL> select decode(id,null,1,0,1,id) from testnvl where fab='S4' and month='2010-06';
no rows selected
从以上结果可看出,在没有符合条件的ID时,SQL并没有按照预期返回1。如果对返回的ID做一下处理,比如加个sum,结果就会改变:
SQL> select decode(sum(id),null,1,0,1,sum(id)) from testnvl where fab='S4' and month='2010-06';
DECODE(SUM(ID),NULL,1,0,1,SUM(ID))
----------------------------------
1
这就是想要的结果了。
为什么加了sum和不加sum会有区别呢,因为decode, nvl等函数是在返回的record上进行计算的,不加sum时返回记录数为0,所以是不会对其做decode,nvl的判断的。加了sum之后,返回记录数为1,只是返回值为null,这样就可以用decode和nvl进行判断了:
SQL> select id from testnvl where fab='S4' and month='2010-06';
no rows selected
SQL> select sum(id) from testnvl where fab='S4' and month='2010-06';
SUM(ID)
----------
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7919512/viewspace-1036751/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/7919512/viewspace-1036751/