Last active
November 11, 2015 21:14
-
-
Save adunstan/3ae53e8b27a8205d2379 to your computer and use it in GitHub Desktop.
dag sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
with recursive | |
dag (depended_on,dependent) as | |
( | |
values | |
('b2'::text,'d1'::text), | |
('d1','d2'), | |
('d2','d3'), | |
('d3','d4'), | |
('b1','a1'), | |
('b2','a1'), | |
('a1','c1'), | |
('d4','a1') | |
-- expected order is: | |
-- c1 a1 d4 d3 d2 d1 b2 with b1 anywhere after a1 | |
) | |
--- continue here ... | |
-- solution from RhodiumToad | |
with recursive r(item,path) as (select dependent, array[]::text[] from dag d1 where not exists (select 1 from dag d2 where d2.depended_on=d1.dependent) union all select depended_on, path || dependent from dag join r on (r.item=dag.dependent)) select * from (select distinct on (item) item,path from r order by item, cardinality(path) desc) s order by cardinality(path); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment