I have a query that is returning systems and areas from my database like so:
SELECT Areas.ID AreaID,
Areas.Name AreaName,
Systems.*
FROM Systems
INNER JOIN Areas ON Areas.ID = Systems.AreaID
WHERE ....
THis returns data that looks like the following:
| AreaID | AreaName | SystemName | ...
| 1 | area1 | sys1 |
| 1 | area1 | sys2 |
| 1 | area1 | sys3 |
| 1 | area1 | sys4 |
| 2 | area2 | sys5 |
| 2 | area2 | sys6 |
I would like to return an additonal column containing the number of systems in each area returned, so that I end up with something like this:
| AreaID | AreaName | SystemName | noOfSystems | ...
| 1 | area1 | sys1 | 4 |
| 1 | area1 | sys2 | 4 |
| 1 | area1 | sys3 | 4 |
| 1 | area1 | sys4 | 4 |
| 2 | area2 | sys5 | 2 |
| 2 | area2 | sys6 | 2 |
I.E. There are 4 systems with the area id of 1 and 2 with the area id of 2.
How can this be done? I’m sure i’ve heard of a built in function that does this but I can’t find quite what I want.
You will want use the aggregate function
COUNT()and thenGROUP BY. This can be done in a correlated subquery:See SQL Fiddle with Demo
Or you can use a subquery that you join to get the total count:
See SQL Fiddle with Demo
This version uses a subquery to get the total count and then you join that back to the
Systemstable to return additional columns, if needed.Or, you can use windowing functions if your RDBMS has this option by using
Count() over():See SQL Fiddle with Demo