列出所有至少有3名工作人员的老板

时间:2012-02-22 09:12:01

标签: sql group-by having

如何查询下表以获取所有老板的名字(即boss_id = staff_id) 谁拥有至少3名员工?我使用havinggroup by,......?

    CREATE TABLE STAFF (STAFF_ID                    CHAR(3),
                        STAFF_NAME              CHAR(20),
                        GENDER                  CHAR(6),
                        DEPARTMENT              CHAR(20),
                        BOSS_ID                 CHAR(3)
                        SALARY                  NUMBER(8,2))

谢谢!

3 个答案:

答案 0 :(得分:2)

我正在使用COUNT(*)>3,因为我认为,除了老板本人,你指的是3名员工。

SELECT a.staff_name
FROM staff a
INNER JOIN (
  SELECT boss_id,COUNT(*) AS cnt_staff FROM staff GROUP BY boss_id HAVING COUNT(*)>3
) b ON a.boss_id=b.boss_id
WHERE a.staff_id=a.boss_id

答案 1 :(得分:1)

select boss_id, staff_name 
from staff 
group by boss_id, staff_name 
having count(staff_id)>=3

答案 2 :(得分:1)

select S.Boss_ID, X.STAFF_NAME
from STAFF S cross apply (Select staff_name from STAFF S2 where S2.staff_id=S.boss_ID) X
group by S.Boss_ID, X.STAFF_NAME
having count(*)>=3