即使没有匹配的记录也会取零

时间:2013-10-08 06:23:09

标签: sql oracle oracle10g

我有表EMP_DETAILS

中的数据
EMPLOYEE_NUMBER      ROLE
NSA5421              CONTRACTOR
NSA390               CONTRACTOR
E8923                EMPLOYEE
E2390                EMPLOYEE

我想零显示,即使没有记录,我尝试了以下但是没有得到理想的结果

SELECT  CASE WHEN cnt IS NULL THEN 0 ELSE cnt END cnt,
        CASE WHEN role IS NULL THEN '0' ELSE role END role
FROM
(SELECT   COUNT (*) cnt, role
     FROM   emp_details
    WHERE   employee_number = 'E3400'
GROUP BY   role)

4 个答案:

答案 0 :(得分:1)

请尝试:

select 
  NVL(y."ROLE", '0') "ROLE",  
  case when y."ROLE" is null then 0 else  COUNT(*) end cnt 
from(
      SELECT 'E3400' employee_number from dual
  )x left join emp_details y on x.employee_number=y.employee_number
group by "ROLE"

答案 1 :(得分:1)

您的内部查询只返回空值而不是空值。

SELECT   COUNT (*) cnt, role
     FROM   emp_details
    WHERE   employee_number = 'E3400'
GROUP BY   role

使用EXISTS条款

答案 2 :(得分:1)

SELECT  CASE WHEN cnt IS NULL THEN 0 ELSE cnt END cnt,
        CASE WHEN role IS NULL THEN '0' ELSE role END role
FROM
(SELECT   COUNT (*) cnt, role
     FROM   emp_details
    WHERE   employee_number = 'E3400'
GROUP BY   ROLE
UNION
SELECT NULL, NULL  FROM dual
WHERE NOT EXISTS
     ( SELECT   COUNT (*) cnt, role
     FROM   emp_details
    WHERE   employee_number = 'E3400'
GROUP BY   ROLE
     )
);

答案 3 :(得分:1)

又一种方式。

SELECT a.role,
       count(b.role)
  FROM emp_details a left outer join emp_details b
    on a.employee_number = b.employee_number
   and a.employee_number = 'E3400'
 group by a.role;

输出:

|      ROLE  | COUNT(B.ROLE)  |
-------------|---------- -----|
| CONTRACTOR |              0 |
|   EMPLOYEE |              0 |

Demo