Here's my attempt, assuming that all children's the_subid refers to the root id, and the root id can be identified by the_id = the_subid:CREATE table dttemp ( the_ID int, the_name varchar(50), the_subid int )insert into dttempselect 1, 'A', 1 union allselect 2, 'Asub', 1 union allselect 3, 'Asub2', 1 union allselect 4, 'B', 4 union allselect 5, 'C', 5 union allselect 6, 'Bsub', 4 union allselect 7, 'Asub3', 1select parent.the_name, count(children.the_id) from (select * from dttemp where the_id = the_subid) parentleft outer join (select * from dttemp where the_id <> the_subid) children on children.the_subid = parent.the_id group by parent.the_name