通过SQL查询获取在多个部门工作的员工数量

时间:2013-10-26 15:17:00

标签: sql sql-server

我正在尝试找出一个查询,该查询显示在1个以上部门工作的员工的数量(金额)。表名和字段在这里:

  • Employee(id_employee,employee_name,salary)
  • Department(id_dept,dept_name,budget)
  • Department_Employee(id_employee,id_dept,workhours_percentage)

假设Department_Employee表的内容为

id_employee  id_dept  workhours_percentage
-----------  -------  --------------------
0001           03         100
0001           04          50
0001           05          60
0002           05          60
0002           09          90
0003           08          80
0004           07          80
0005           06          60
0006           05          70
0007           04          75
0008           10          95
0009           02          25
0010           01          40

使用正确的查询,结果应为2(员工),因为有2名员工在多个部门工作

  • 员工0001在3个部门工作
  • 员工0002在两个部门工作


我尝试了以下查询

SELECT COUNT(DISTINCT id_employee)
FROM Department_Employee
GROUP BY id_employee
HAVING COUNT(id_employee)>1

但结果不对。

请帮帮我。

感谢。

4 个答案:

答案 0 :(得分:3)

让所有在多个部门工作的员工:

SELECT id_employee, COUNT(*)
FROM Department_Employee
GROUP BY id_employee
HAVING COUNT(*)>1

计算它们:

;
WITH cte As
(
    SELECT id_employee
    FROM Department_Employee
    GROUP BY id_employee
    HAVING COUNT(*)>1
)
SELECT COUNT(*) FROM cte

答案 1 :(得分:1)

SELECT COUNT(*)
FROM
(
SELECT id_employee, COUNT(*) AS CNT
FROM Department_Employee
GROUP BY id_employee
) AS T
WHERE CNT > 1

答案 2 :(得分:0)

select e.id_employee, count(e.id_dep) from Department_Employee e group by e.id_employee having count(e.id_dep)>1 ;

在此我尝试首先尝试通过id_employee获取dept id组的计数 并且我们的要求是使用count(e.id_dep)> 1来查找属于多个部门的员工以检索相同的人员。

答案 3 :(得分:0)

SELECT COUNT(*)
FROM (
  SELECT id_employee, COUNT(*) AS CNT
  FROM Department_Employee
  GROUP BY id_employee
) AS T
WHERE CNT > 1