oracle:案例:I / Elsef查询

时间:2016-12-06 15:24:15

标签: oracle

我正在执行一个select语句,如下所示

Select case 
         when count(*) = 0 then 'Pass' 
       end as Test_Result
  from Table Name 
 where condition;

我想要输出如下

If count(*)=0 then Result should be 'Pass'

否则我想要这个查询的输出。我的意思是输出低于一个

Select Count(*)
  from Table Name 
 where condition;

2 个答案:

答案 0 :(得分:3)

此处的一个选项是执行没有WHERE条件的查询,然后使用条件聚合来获取ELSE条件中显示的计数。

SELECT CASE WHEN COUNT(*) = 0 THEN 'Pass'
            ELSE CAST(SUM(CASE WHEN condition THEN 1 ELSE 0 END) AS VARCHAR2(30))
       END AS Test_Result
FROM yourTable

答案 1 :(得分:0)

一种方法可能是:

<强>设置:

create table emptyTab ( a number);
create table notEmptyTab ( a) as ( select 1 from dual );

这应该可以解决问题:

SQL> select case
  2           when count(*) = 0 then 'Pass'
  3           else to_char(count(*))
  4         end
  5  from emptyTab
  6  where a = 1       ;

CASEWHENCOUNT(*)=0THEN'PASS'ELSETO_CHAR(
----------------------------------------
Pass

SQL> select case
  2           when count(*) = 0 then 'Pass'
  3           else to_char(count(*))
  4         end
  5  from notEmptyTab
  6  where a = 1;

CASEWHENCOUNT(*)=0THEN'PASS'ELSETO_CHAR(
----------------------------------------
1

SQL> select case
  2           when count(*) = 0 then 'Pass'
  3           else to_char(count(*))
  4         end
  5  from notEmptyTab
  6  where a = 2;

CASEWHENCOUNT(*)=0THEN'PASS'ELSETO_CHAR(
----------------------------------------
Pass