Advertisement
happy-barney

sql-paths-for-daxim

Jun 24th, 2020
530
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 (row, depth, parent_row, vertex, successor) as (
  19.         select row_number() over (), 1, 0::bigint, dag.vertex, dag.successor
  20.                 from head
  21.                 join dag on (dag.vertex = head.vertex)
  22.         union all
  23.         select row_number() over (), depth + 1, row, dag.vertex, dag.successor
  24.                 from paths
  25.                 join dag on (dag.vertex = paths.successor)
  26. ),
  27. result (path_id, parent_row, depth, vertex) as (
  28.         select row_number() over (), parent_row, depth, vertex
  29.                 from paths
  30.                 where successor is null
  31.         union all
  32.         select result.path_id, paths.parent_row, paths.depth, paths.vertex
  33.                 from result
  34.                 join paths on (paths.row = result.parent_row and paths.depth = result.depth - 1)
  35. )
  36. select path_id, depth, vertex
  37.         from result
  38.         order by 1, 2
  39. ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement