-1

How can I query the table below to get the names of all bosses (ie boss_id = staff_id) who have at least 3 staff? Do I use having, group 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))

Thanks!

Leigh
  • 28,765
  • 10
  • 55
  • 103
user1225281
  • 51
  • 1
  • 1
  • 3

3 Answers3

2

I'm using COUNT(*)>3 because I assume, that you mean 3 staff except the boss himself.

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
rabudde
  • 7,498
  • 6
  • 53
  • 91
1
select boss_id, staff_name 
from staff 
group by boss_id, staff_name 
having count(staff_id)>=3
rene
  • 41,474
  • 78
  • 114
  • 152
mindandmedia
  • 6,800
  • 1
  • 24
  • 33
  • its at position 2 in your result set. if you just want the staff_name, just leave out the boss_id in the select and the group by. then the staff_name is your only result. – mindandmedia Feb 22 '12 at 09:18
  • but if in the case where i look for the name of the boss, can i do : select STAFF_ID from staff where STAFF_ID = BOSS_ID group by BOSS_ID having count(STAFF_ID)>=3 – user1225281 Feb 22 '12 at 09:22
  • @user1225281 no, that's not possible – rabudde Feb 22 '12 at 12:08
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
Diego
  • 34,802
  • 21
  • 91
  • 134