6

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

  • Employee(id_employee、employee_name、薪水)
  • Department(id_dept、dept_name、预算)
  • 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 在 2 个部门工作


我尝试了以下查询

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

但结果不对。

请帮帮我。

谢谢。

4

4 回答 4

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
于 2013-10-26T15:24:44.397 回答
3
SELECT COUNT(*)
FROM
(
SELECT id_employee, COUNT(*) AS CNT
FROM Department_Employee
GROUP BY id_employee
) AS T
WHERE CNT > 1
于 2013-10-26T15:25:37.813 回答
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 获取部门 ID 组的计数,并且我们的要求是找到属于多个部门的员工,使用 count(e.id_dep)>1 来检索相同的部门。

于 2018-02-21T08:30:35.170 回答
0
SELECT COUNT(*)
FROM (
  SELECT id_employee, COUNT(*) AS CNT
  FROM Department_Employee
  GROUP BY id_employee
) AS T
WHERE CNT > 1
于 2020-04-09T12:06:06.687 回答