如何根据内部查询添加where子句

时间:2012-05-29 06:58:11

标签: sql oracle

我正在尝试编写一个查询来获取每个部门的员工数量。这我正在使用内部查询。 我面临的问题是我需要过滤出数量小于10的记录。 以下是我的查询的外观 -

SELECT 
   DPT.ID, 
   DPT.NAME, 
   (SELECT COUNT(1) FROM EMPLOYEE E WHERE E.DEPARTMENT_ID=DPT.ID) EMP_COUNT
FROM 
   DEPARTMENT DPT
WHERE 
   EMP_COUNT >=10; -- this part is not working

任何人都可以建议我可以替换EMP_COUNT >=10代替吗? 提前谢谢。

3 个答案:

答案 0 :(得分:4)

为什么使用子查询?在大多数RDBMS-es上,这可能会更快

SELECT     DPT.ID 
,          DPT.NAME 
,          COUNT(*) EMP_COUNT
FROM       DEPARTMENT DPT
INNER JOIN EMPLOYEE E
ON         DPT.ID = E.DEPARTMENT_ID
GROUP BY   DPT.ID 
,          DPT.NAME
HAVING     COUNT(*) >= 10;

答案 1 :(得分:1)

SELECT DPT.ID, DPT.NAME, DEPT_EMP_COUNT
FROM DEPARTMENT DPT, (SELECT E.DEPARTMENT_ID , COUNT(1) AS DEPT_EMP_COUNT 
                      FROM EMPLOYEE E
                      GROUP BY E.DEPARTMENT_ID ) EMP_COUNT 
WHERE EMP_COUNT.DEPARTMENT_ID = DPT.ID AND DEPT_EMP_COUNT > 10; 

答案 2 :(得分:0)

试试这个

select dept.deptId,
dept.deptName,
count(emp.empid) as numb_of_emps
from department dept inner join employee emp
on dept.deptid = emp.deptid
group by dept.deptid,dept.deptName
having count(emp.empid) >= 10