客戶需求是咨詢如何用SQL結合decode函數實現條件判斷,比如當某一列數值大於500,對應類型“大於500”;當某一列數值小於500,對應類型“小於500”。
實際decode函數無法實現這個功能,實現要用到case when,為此我構造一個簡單的示例來直觀演示:
create table test302(id number, name varchar2(20));
insert into test302 values (499, 'aaa');
insert into test302 values (500, 'bbb');
insert into test302 values (501, 'ccc');
commit;
測試包含case when的SQL:
select u.id,u.name,
(case
when u.id>500 then '大於500'
when u.id<500 then '小於500'
else '等於500'
end
)type
from test302 u;
得到結果如下:
SQL> select u.id,u.name,
2 (case
3 when u.id>500 then '大於500'
4 when u.id<500 then '小於500'
5 else '等於500'
6 end
7 )type
8 from test302 u;
ID NAME TYPE
---------- -------------------- ---------
499 aaa 小於500
500 bbb 等於500
501 ccc 大於500
滿足客戶用SQL實現某列值條件判斷的需求,我們可以看到這個例子非常簡單,但這也是大多數運維dba的短板--SQL相關知識欠缺,還是要學習積累的。