Advertisement
happy-barney

sql-paths-for-daxim-pgsql

Jun 24th, 2020
547
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. with recursive
  2. dag (vertex, successor) as (values
  3.         ('alpha', 'bravo'),
  4.         ('bravo', 'charlie'),
  5.         ('charlie', 'delta'),
  6.         ('delta', null),
  7.         ('alpha', 'echo'),
  8.         ('echo', 'foxtrot'),
  9.         ('bravo', 'foxtrot'),
  10.         ('foxtrot', null),
  11.         ('alpha', 'golf'),
  12.         ('golf', 'hotel'),
  13.         ('hotel', null)
  14. ),
  15. head (vertex) as (
  16.         select vertex from dag except select successor from dag
  17. ),
  18. paths (path, successor) as (
  19.         select array[dag.vertex], dag.successor
  20.                 from head
  21.                 join dag on (dag.vertex = head.vertex)
  22.         union all
  23.         select array_append(paths.path, dag.vertex), dag.successor
  24.                 from paths
  25.                 join dag on (dag.vertex = paths.successor)
  26. ),
  27. result_paths (path_id, path) as (
  28.         select row_number() over (), path
  29.                 from paths
  30.                 where successor is null
  31. ),
  32. result (path_id, depth, vertex) as (
  33.         select path_id, p.nr, p.elem
  34.                 from result_paths
  35.                 left join lateral unnest (path) with ordinality as p(elem, nr) on true
  36. )
  37. select * from result order by 1,2;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement