Question

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

  1. The 'Staff' table: staffno | fname | lname | position | sex | dob | salary | branchno

  2. the 'branch' table: branchno | street | city | postcode

Thank you kindly

Was it helpful?

Solution

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 selectstatement.

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 fromstatement.

And finally, you only want from a specific branch so what do you do? You filter the results with a whereclause.

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 joinbetween the tables means that you'll get all rows from branch and the matching rows from staff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top