列出在同一部门工作的员工对

时间:2016-04-20 17:08:59

标签: sql database oracle

在oracle SQL中如何列出在同一部门工作的员工对...我的员工表如下:

employeeid  department
    101        2
    102        2
    103        3
    104        3
    105        4

2 个答案:

答案 0 :(得分:2)

您可以通过

获得拥有多名员工的部门的所有员工
SELECT * FROM employees
WHERE department IN
(
  SELECT department
  FROM employees
  GROUP BY department
  HAVING COUNT(*) > 1
)

或使用LISTAGG在列表中显示ID:

  SELECT 
    department,
    LISTAGG(employeeid, ', ') AS EmployeeList
  FROM employees
  GROUP BY department
  HAVING COUNT(*) > 1

答案 1 :(得分:0)

如果您的表名为t,则可以“列出”在同一部门中使用自联接工作的员工对,如下所示:

select t1.employeeid as employee1, t2.employeeid as employee2, department
from t t1 join t t2 using (department)
where t1.employeeid < t2.employeeid

公平警告:对于拥有大量员工的部门,对的数量渐渐增长,就像该部门员工人数的平方的1/2倍,因此您可能会获得大量的行数。真正的“输入表。

如果需要,您可以根据需要对结果进行排序,例如添加以下行:

order by department, employee1, employee2