MySQL查询没有显示正确的结果

时间:2015-04-15 16:28:22

标签: mysql

我想指定拥有> = 3名员工的部门,在各部门之后打印部门员工名单。

我有两张桌子:

Employee_Table (Employee_Number, Employee_Name, Department_Number)
Department (Department_Number, Department_Name)

这是我的SQL代码:

SELECT  ET.Department_Number,ET.Employee_Name
FROM dbo.Employee_Table ET
GROUP BY ET.Department_Number,ET.Employee_Name
HAVING COUNT(ET.Department_Number) >= 3

但如果我跑的话,什么都没有出现:

SELECT  ET.Department_Number
FROM dbo.Employee_Table ET
GROUP BY ET.Department_Number
HAVING COUNT(ET.Department_Number) >= 3

我有一个正确的结果,即101和105,但与Employee_Name结合我无法得到正确的结果。

3 个答案:

答案 0 :(得分:0)

在SQL Server中,我会使用CTE和JOIN。

WITH Departments AS (
  SELECT  ET.Department_Number
  FROM dbo.Employee_Table ET
  GROUP BY ET.Department_Number
  HAVING COUNT(ET.Department_Number) >= 3
)

SELECT D.Department_Number, ET.Employee_Name
FROM dbo.Employee_Table ET
JOIN Departments ON ET.Department_Number = D.Department_Number
ORDER BY D.Department_Number

看起来怎么样?

答案 1 :(得分:0)

在这种情况下,您需要一个子查询来获得拥有3名或更多员工的部门。这应该可以解决问题:

SELECT  
ET.Department_Number,
ET.Employee_Name
FROM dbo.Employee_Table ET
join
(   Select department_number, count(department_number)
    from dbo.Employee_Table
    group by department_number
    HAVING COUNT(Department_Number) >= 3
) dept_having_3
on et.department_number = dept_having_3.department_number   

答案 2 :(得分:0)

SELECT  
ET.Department_Number,
ET.Employee_Name
FROM Employee_Table ET
WHERE Department_Number IN
(   SELECT Department_Number
    FROM Employee_Table
    GROUP by Department_Number
    HAVING COUNT(*) >= 3
)