0

我在表 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

4 回答 4

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"
于 2013-10-08T06:32:15.540 回答
1

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

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

使用 EXISTS 子句

于 2013-10-08T06:34:21.933 回答
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
     )
);
于 2013-10-08T06:35:02.737 回答
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 |

演示

于 2013-10-08T06:39:13.543 回答