Reputation: 7
I'm trying to count staff that belong to certain branch in sql, so branch X has Y number of employees for example. There are two tables I need to query number 1. and 2. below. I want to achieve the following:branchno | number of staff in that branch
The 'Staff' table: staffno | fname | lname | position | sex | dob | salary | branchno
the 'branch' table: branchno | street | city | postcode
Thank you kindly
Upvotes: 0
Views: 108
Reputation: 44901
This is a really basic query, and if you have problems solving it, just break it down step by step:
What is it you want to get? A count of people in a certain branch. How do you choose what information to display? With a select
statement.
What do you want to do with the information before you show it? You want to count it with a count()
aggregate function.
Where do you get the data from? A table, selected with a from
statement.
And finally, you only want from a specific branch so what do you do? You filter the results with a where
clause.
And putting it all together you get this:
SELECT COUNT(staffno) FROM Staff WHERE branchno = 1
If you want the branch with number 1.
Edit: I just noticed the comment you made about branches without employees, and taking that into account you need the branch table too.
SELECT b.branchno, COUNT(staffno) AS StaffCount FROM branch b
LEFT JOIN staff s ON b.branchno = s.branchno
-- WHERE b.branchno = 1 -- optional filter
GROUP BY b.branchno
Using a left join
between the tables means that you'll get all rows from branch and the matching rows from staff.
Upvotes: 1