如何选择在03和04两个部门工作过的员工。在这个片段中,只有emp 0001和0004在03和04部门都有效。
id_employee id_dept workhours_percentage
----------- ------- --------------------
0001 03 100
0001 04 50
0001 05 60
0002 05 60
0002 09 90
0002 08 80
0003 07 80
0003 06 60
0003 05 70
0004 03 75
0004 04 95
0004 02 25
答案 0 :(得分:1)
试试这个:
SELECT id_employee
FROM Your_Table
WHERE id_dept IN('03','04')
GROUP BY id_employee
HAVING COUNT(DISTINCT id_dept)=2
<强>输出:强>
id_employee
0001
0004
答案 1 :(得分:0)
您可以使用GROUP_CONCAT
功能和GROUP BY
来实现此目的:
SELECT EMP_ID, GROUP_CONCAT(DISTINCT DEPT ORDER BY DEPT ASC SEPARATOR '; ') DEPTS FROM ( SELECT '0001' EMP_ID, '03' DEPT, '100' WORK_PER FROM DUAL UNION ALL SELECT '0001' EMP_ID, '04' DEPT, '50' WORK_PER FROM DUAL UNION ALL SELECT '0001' EMP_ID, '05' DEPT, '60' WORK_PER FROM DUAL UNION ALL SELECT '0002' EMP_ID, '05' DEPT, '60' WORK_PER FROM DUAL UNION ALL SELECT '0002' EMP_ID, '09' DEPT, '90' WORK_PER FROM DUAL UNION ALL SELECT '0002' EMP_ID, '08' DEPT, '80' WORK_PER FROM DUAL UNION ALL SELECT '0003' EMP_ID, '07' DEPT, '80' WORK_PER FROM DUAL UNION ALL SELECT '0003' EMP_ID, '06' DEPT, '60' WORK_PER FROM DUAL UNION ALL SELECT '0003' EMP_ID, '05' DEPT, '70' WORK_PER FROM DUAL UNION ALL SELECT '0004' EMP_ID, '03' DEPT, '75' WORK_PER FROM DUAL UNION ALL SELECT '0004' EMP_ID, '04' DEPT, '95' WORK_PER FROM DUAL UNION ALL SELECT '0004' EMP_ID, '02' DEPT, '25' WORK_PER FROM DUAL ) EMP GROUP BY EMP_ID HAVING DEPTS LIKE '%03; 04%';
类似于Oracle的LISTAGG
函数,它按照上述顺序聚合所述列值,并使用分隔符,在这种情况下为'; '
。我们正在汇总DEPT
列并使用EMP_ID
对其进行分组,最后检查汇总列是否将所需的两个部门分隔为'; '
。
希望这有助于解释。 :)