我一直在摸着这个。
这个问题让我更接近,但我的情况有点复杂。 How do I find duplicate values in a table in Oracle?
假设我有一个表EMPLOYEE,我想知道哪些员工在多个部门工作。我的表具有员工ID和他们工作的部门。当员工在多个部门工作时,他们的员工ID将被列为多个记录。我不想只计算两次列出的员工。我需要知道这个部门列表与部门列表中的工作量有多少。
例如,如果我的表是:
Employee ID | Department
1 Accounting
1 Marketing
2 Accounting
3 Finance
4 Programming
部门名单A是
部门名单B是
然后查询结果将是
Employee ID | Department
1 Accounting
1 Marketing
或
Employee ID | Count(Department)
1 2
因为员工1在名单A和名单B的部门工作。
答案 0 :(得分:2)
我会用映射来解决这个问题:
with mapping as (
select 'Accounting' as department, 'A' as grouping from dual union all
select 'Finance' as department, 'A' as grouping from dual union all
select 'Marketing' as department, 'B' as grouping from dual union all
select 'Programming' as department, 'B' as grouping from dual
)
select employeeid, count(distinct m.grouping)
from t join
mapping m
on t.department = m.department
group by employeeid;
注意:您可能希望将此信息存储在另一个表中,或者作为Departments
表中的属性存储。
如果您希望独奏部门映射到自己:
select t.employeeid, count(distinct coalesce(m.grouping, t.department))
from t join
mapping m
on t.department = m.department
group by t.employeeid;
如果您希望不在表中的其他部门组合在一起:
select t.employeeid, count(distinct coalesce(m.grouping, 'UNKNOWN MAPPING'))
from t join
mapping m
on t.department = m.department
group by t.employeeid;
答案 1 :(得分:1)
如果我理解你所追求的是什么,你可以在HAVING
条款中使用条件聚合:
SELECT Employee_ID, COUNT(DISTINCT Department) AS Dept_Count
FROM YourTable
GROUP BY Employee_ID
HAVING MAX(CASE WHEN Department IN ('Accounting','Finance') THEN 1 ELSE 0 END) = 1
AND MAX(CASE WHEN Department IN ('Marketing','Programming') THEN 1 ELSE 0 END) = 1