Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(*) in SQL

Tags:

sql

I understand how count(*) in SQL when addressing one table but how does it work on inner joins?

e.g.

SELECT branch, staffNo, Count(*)
FROM Staff s, Properties p 
WHERE s.staffNo = p.staffNo
GROUP BY s.staffNo, p.staffNo

staff contains staffNo staffName

properties contains property management details (i.e. which staff manages which property)

This returns the number of properties managed by staff, but how does the count work? As in how does it know what to count?

like image 306
user559142 Avatar asked May 26 '11 12:05

user559142


1 Answers

It's an aggregate function - as such it's managed by your group by clause - each row will correspond to a unique grouping (i.e. staffNo) and Count(*) will return the number of records in the join that match that grouping.

So for example:

 SELECT branch, grade, Count(*)
 FROM Staff s, Properties p 
 WHERE s.staffNo = p.staffNo
 GROUP BY branch, grade

would return the number of staff members of a given grade at each branch.

 SELECT branch, Count(*)
 FROM Staff s, Properties p 
 WHERE s.staffNo = p.staffNo
 GROUP BY branch

would return the total number of staff members at each branch

 SELECT grade, Count(*)
 FROM Staff s, Properties p 
 WHERE s.staffNo = p.staffNo
 GROUP BY grade

would return the total number of staff at each grade

like image 130
BonyT Avatar answered Sep 23 '22 23:09

BonyT