oracle數據庫查詢語句case的用法


實現功能:

1.先查詢status=2的記錄,如果查詢到記錄則返回第一條記錄的Product_Name;
2.如果查詢不到status=2的記錄,則判斷status=1的記錄是否存在,不存在則返回“請耐心等待!”,存在則返回“拆煙完畢!”

 

實現思路:

1、使用case語句返回不同的內容:

case語句格式:

case

when 判斷語句1 then 返回1

when 判斷語句2 then 返回2

……

else 返回n

end

 

2、解決無記錄時需要返回一條null的數據:

select Product_name 

from v_supply_sj 

union select null from dual

 

3、解決有記錄的情況下還會附帶一條null數據的問題:

通過判斷初始查詢結果count(*)是否等於0來決定返回的記錄數

 

 最終查詢語句:

select case 
when t1.Product_name is not null then t1.product_name  
when t2.Product_name is not null then '拆煙完畢' 
else '請耐心等待' end as ledtext from  
(select rownum as q, Product_name from (select  Product_name from( select rownum as p,Product_name from v_supply_sj where to_addr = 'SJ03' and bill_type=5 and status = 2 and up_down = '1'  ) where rownum<=1  union select null from dual )
where rownum<= case 
when (select count(*) from (select Product_name from( select rownum as p,Product_name from v_supply_sj where to_addr = 'SJ03' and bill_type=5 and status = 2 and up_down = '1'  ) where rownum<=1  union select null from dual ))=1 
then 1 else
(select count(*) from (select Product_name from( select rownum as p,Product_name from v_supply_sj where to_addr = 'SJ03' and bill_type=5 and status = 2 and up_down = '1'  ) where rownum<=1  ) ) end )  t1 left join 
(select rownum as q, Product_name from (select  Product_name from( select rownum as p,Product_name from v_supply_sj where to_addr = 'SJ03' and bill_type=5 and status = 1 and up_down = '1'  ) where rownum<=1  union select null from dual )
where rownum<= case 
when (select count(*) from (select Product_name from( select rownum as p,Product_name from v_supply_sj where to_addr = 'SJ03' and bill_type=5 and status = 1 and up_down = '1'  ) where rownum<=1  union select null from dual ))=1 
then 1 else
(select count(*) from (select Product_name from( select rownum as p,Product_name from v_supply_sj where to_addr = 'SJ03' and bill_type=5 and status = 1 and up_down = '1'  ) where rownum<=1  ) ) end )   t2 on t1.q=t2.q 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM