简体   繁体   中英

Checking how many people a staff member supervises

I've been asked to make a new table called SupervisorStaff showing a column of staffID and another column of how many staff members that staff member currently supervise. I already have a table called staff with the columns - staffID and SupervisorID among other things so I planned to make my new table using the information stored inside it. The SupervisorID is the id of the staff member that supervises them. For example, a staff member with the id - 3 could have a SupervisorID - 5, which means staff member 5 is the person supervising them. What I was trying to do was to make a count of the supervisor ids for each staffID to show what the total staff members each staffID supervises is. I did this:

CREATE VIEW SupervisorStaff AS
    SELECT Staff.StaffID, COUNT(Staff.SupervisorID) AS "No. of staff supervised"
    FROM Staff
    GROUP BY (Staff.SupervisorID)
    ORDER BY (Staff.StaffID)

However, that doesn't work. I'm pretty new to databases, so I don't really know where I went wrong or where to go from here.

I would like the end result to look like this:

staff ID No of staff supervised
1 4
2 1

A list of all staff members (as shown by their IDs) and how many people they supervise (as shown by the number to their right).

The table I'm currently working off and using data from looks like this:

staff name staff ID SupervisorID
John Smith 1 5
rachel lin 2 5
richard way 3 1

A list of all the staff members and who supervises them.

So you want to see how many people each person supervises.

You're on the right track with a group by but your select value should contain:

  • values used in your group by
  • aggregates like count

Something like this:

select
supervisorid as 'Supervisor', count(staffid) as 'Nr of people supervised'
from staff
group by supervisorid
order by supervisorid

If this is your STAFF table:

CREATE TABLE STAFF(NAME varchar(20), ID int, SUPERVISOR_ID int);
INSERT INTO STAFF VALUES('Jon',1,5);
INSERT INTO STAFF VALUES('Rachel',2,5);
INSERT INTO STAFF VALUES('Richard',3,1);

Then this is the query for getting the result you are looking for:

SELECT SUPERVISOR_ID, COUNT(*) AS NO_STAFF_SUPERVISED 
FROM STAFF 
GROUP BY SUPERVISOR_ID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM