I have two tables defined below (note that the Regions table is recursive and that the recursion can potentially have many levels).
Regions
| Id | ParentId | Name |
|---|---|---|
| 1 | null | EU |
| 2 | 1 | Germany |
| 3 | 1 | France |
Cities
| Id | Name | RegionId |
|---|---|---|
| 1 | Berlin | 2 |
| 2 | Hamburg | 2 |
| 3 | Paris | 3 |
| 4 | Nice | 3 |
I want to see how many cities there are in a particular region. Desired output below:
| Region | CityCount |
|---|---|
| EU | 4 |
| Germany | 2 |
| France | 2 |
This query gives me the count of cities in every child region, but how do I join in the recursive table to also get the parent (in this case EU) region?
select R.Name, count(C.Id)
from Regions R
join Cities C on C.RegionId = R.Id
group by R.Name
having count(C.Id) > 1
I've tried to simplify a real-world problem I'm facing, this is obviously the simplification.