如果SELECT语句没有结果,则使用CASE标记否

时间:2016-03-30 08:29:51

标签: sql oracle oracle11g

是否可以打印" no"如果没有找到结果

SELECT mobileno,  
 CASE
    WHEN region = '1234' 
    THEN 'Yes'
    ELSE 'NO'
  END  
FROM subscriber
WHERE region = '1234'
and  status = 1
and mobileno in (77777,88888)

目前只打印1行,如

77777,是

但我想跟随

77777,yes
88888,no

更新:如果我们删除区域条件,则一个mobileno(如7777)可能属于两个区域,那么7777将获得打印,NO和YES将在两行中打印。

样本数据

sr.No, Name, mobileno, region, status
1,     abc,  77777,    1234,    1
2,     xyz,  88888,    1222,    1
3,     tyu,  22342,    9898,    1
4,     abc,  77777,    8787,    1

Sample OutPut

77777, Yes
88888, No

1 个答案:

答案 0 :(得分:2)

你可以创造'通过选择双重和左连接来表:

SELECT t.dummy_num,
       CASE WHEN s.mobileno is null then 'No' else 'Yes' end
FROM (SELECT 77777 as dummy_num from dual
      UNION select 88888 from dual) t
LEFT JOIN subscriber s
 ON(t.dummy_num = s.mobileno and s.region = '1234' and s.status = 1 )

编辑:您也可以像这样动态地执行:

SELECT t.mobileno,
       CASE WHEN s.mobileno is null then 'No' else 'Yes' end
FROM (select distinct mobileno from subscriber) t
LEFT JOIN subscriber s
 ON(t.mobileno= s.mobileno and s.region = '1234' and s.status = 1 )
WHERE t.mobileno IN(777,888,.....)