Reputation: 5347
I have a table structure, which, simplified, looks something like this.
grandparents
id
name
parents
id
grandparent_id
name
children
id
parent_id
name
I know, I can count the number of children a parent has like this:
select
name,
( select count (*) from children c where c.parent_id = p.id ) as count
from p parents;
My question is, how do I count the number of children that are related to a grandparent. The table structure cannot be changed, and I want a single SELECT statement. Is that possible?
Thanks in advance.
Upvotes: 0
Views: 219
Reputation: 16351
This should do the trick, even in weird family trees (parents being brothers for example):
SELECT gp.id,
gp.name,
COUNT(DISTINCT c.id)
FROM grandparents gp
INNER JOIN parents p
ON p.grandparent_id = gp.id
INNER JOIN children c
ON c.parent_id = p.id
GROUP BY gp.id,
gp.name
See fiddle (no Firebird engine available, but this code is SQL standard compliant).
Upvotes: 2