Skip to content

Instantly share code, notes, and snippets.

@amacal
Created November 2, 2020 17:36
Show Gist options
  • Save amacal/a3a134e74a46b45fea4bb7916b27c452 to your computer and use it in GitHub Desktop.
Save amacal/a3a134e74a46b45fea4bb7916b27c452 to your computer and use it in GitHub Desktop.
with recursive hierarchy(id, id_prev, length) as
(
-- only roots
select id, id_prev, 1 as length
from ecds_db.playground.orders
where id_prev is null
union all
-- only joinable children
select o.id, o.id_prev, p.length + 1
from ecds_db.playground.orders o
join hierarchy p on p.id = o.id_prev
)
select length, count(1)
from hierarchy
group by length
order by 1 desc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment