除了此CASE语句中概述的条件外,查询还返回NULL值。我尝试在CASE中插入IS NOT NULL,但不断收到与关键字相关的错误。我很感激你的帮助。 Oracle SQL:
SELECT DISTINCT A.DEPTID,
CASE
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 1')
THEN 'Employee 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 2')
THEN 'Employee 2'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 1')
THEN 'Manager 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 2')
THEN 'Manager 2'
END AS MISSING_JOBTYPE
FROM MYTABLE A
答案 0 :(得分:0)
您似乎希望部门缺少员工类别。我会使用条件聚合和having
子句:
select deptid,
sum(case when rolename = 'Employee 1' then 1 else 0 end) as nume1,
sum(case when rolename = 'Employee 2' then 1 else 0 end) as nume2,
sum(case when rolename = 'Manager 1' then 1 else 0 end) as numm1,
sum(case when rolename = 'Manager 2' then 1 else 0 end) as numm2
from mytable a
group by deptid
having nume1 = 0 or nume2 = 0 or numm1 = 0 or numm2 = 0;
这将使所有部门至少缺少这些员工角色中的一个。请注意,某些数据库不支持having
子句中的别名,因此您必须重复定义表达式或使用子查询。
答案 1 :(得分:0)
你有两种抑制空值的方法,一种是简短的:
SELECT DISTINCT A.DEPTID,
CASE
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 1')
THEN 'Employee 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 2')
THEN 'Employee 2'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 1')
THEN 'Manager 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 2')
THEN 'Manager 2'
ELSE 'Once upon a time NULL used to live here...'
END AS MISSING_JOBTYPE
FROM MYTABLE A
另一个很长:
SELECT DISTINCT A.DEPTID,
CASE
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 1')
THEN 'Employee 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 2')
THEN 'Employee 2'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 1')
THEN 'Manager 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 2')
THEN 'Manager 2'
END AS MISSING_JOBTYPE
FROM MYTABLE A
WHERE CASE
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 1')
THEN 'Employee 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Employee 2')
THEN 'Employee 2'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 1')
THEN 'Manager 1'
WHEN NOT EXISTS (SELECT B.* FROM MYTABLE B
WHERE A.DEPTID = B.DEPTID
AND B.ROLENAME = 'Manager 2')
THEN 'Manager 2'
END IS NOT NULL