选择拥有2名以上薪水大于1000的员工的部门名称

时间:2011-01-10 11:07:00

标签: sql

如何在SQL中执行以下操作

“选择员工人数超过2且薪水大于1000的员工名称?”

DeptId DeptName
------ --------
1          one
2          two
3        three

EmpId DeptId Salary
----- ------ ------
121      1    2000
122      1    2000
123      1    5000
124      1    4000
131      2    2000
132      2    6000
133      2    1000
134      2    1000
125      3    1000
126      3   20000


RESULT: one

8 个答案:

答案 0 :(得分:12)

这样的事情怎么样?

SELECT D.DeptName FROM
Department D WHERE (SELECT COUNT(*) 
                    FROM Employee E 
                    WHERE E.DeptID = D.DeptID AND
                            E.Salary > 1000) > 2

答案 1 :(得分:4)

SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
     FROM DEPT AS D,EMPLOYEE AS E
     WHERE D.DEPTID=E.DEPTID AND SALARY>1000
     GROUP BY D.DEPTID
     )
WHERE TOTEMP>2;

答案 2 :(得分:2)

select min(DEPARTMENT.DeptName) as deptname 
from DEPARTMENT
inner join employee on
DEPARTMENT.DeptId = employee.DeptId
where Salary > 1000
group by (EmpId) having count(EmpId) > =2 

答案 3 :(得分:1)

希望这会有所帮助

select DeptName from DEPARTMENT inner join EMPLOYEE using (DeptId) where Salary>1000 group by DeptName having count(*)>2

答案 4 :(得分:0)

select deptname from dept_1
where exists
(
SELECT DeptId,COUNT(*)        
FROM emp_1  
where salary>1000
and emp_1.deptid=dept_1.deptid   
GROUP BY DeptId 
having count(*)>2)

答案 5 :(得分:0)

select D.DeptName from [Department] D where D.DeptID in 
( 
    select E.DeptId from [Employee] E
    where E.Salary > 1000
    group by E.DeptId
    having count(*) > 2
)

答案 6 :(得分:0)

1:列出一年内收入超过RS.100000的所有员工的名称。

2:将雇员的姓名命名为员工I.D

的部门

答案 7 :(得分:-2)

我的主要建议是避开HAVING条款(见下文):

WITH HighEarners AS
     ( SELECT EmpId, DeptId
         FROM EMPLOYEE
        WHERE Salary > 1000 ), 
     DeptmentHighEarnerTallies AS 
     ( SELECT DeptId, COUNT(*) AS HighEarnerTally
         FROM HighEarners
        GROUP 
           BY DeptId )
SELECT DeptName
  FROM DEPARTMENT NATURAL JOIN DeptmentHighEarnerTallies
 WHERE HighEarnerTally > 2;

早期的SQL实现缺少派生表,而HAVING是其最明显缺点之一的解决方法(如何从SELECT子句中选择set函数的结果)。一旦派生表成为一种东西,HAVING的需求就消失了。遗憾的是,HAVING本身并没有消失(而且永远不会消失)因为标准SQL中没有任何东西被删除。没有必要学习HAVING,我鼓励刚刚起步的程序员避免使用这种历史宿醉。

相关问题