Q:

Determining child counts of hierarchical paths

I have a table consisting of the following columns:
child_count | path
------------+-----
            | /
            | /a
            | /a/a
            | /a/b
            | /a/b/c
            | /b

Presently, only the path column has data.  I would like to know of an SQL (preferably PostgreSQL) query that would be able to determine the child count of each path as follows:
child_count | path
------------+-----
2           | /
2           | /a
0           | /a/a
1           | /a/b
0           | /a/b/c
0           | /b

A:

Andomar beat me while I was editing, but I'll post my solution anyway as it uses some PostgreSQL specific stuff.

with path_elements as (
  select path, array_length(string_to_array(path, '/'),1) as element_count
  from path_table
)
select parent_path, count(child_path) 
from (
  select p.path as parent_path,
         c.path as child_path
  from path_elements p
    left join path_elements c 
              on p.element_count + 1 = c.element_count 
             and substring(c.path, 1, length(p.path)) = p.path
) t
group by parent_path
order by parent_path;

