Created
July 24, 2014 02:50
-
-
Save wishdev/635f7a839877d79a6781 to your computer and use it in GitHub Desktop.
Recursive grouping and bucket assignment
This file contains 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 | |
-- Shamelessly stolen from | |
-- http://www.postgresql.org/docs/9.3/static/queries-with.html | |
recursive groups (key1, key2, path, cycle) | |
AS ( | |
select key1, | |
key2, | |
ARRAY[ROW(key1, key2)], | |
false | |
from graph | |
union all | |
select a.key1, | |
b.key2, | |
path || ROW(a.key1, b.key2), | |
ROW(a.key1, b.key2) = ANY(PATH) | |
from graph a, | |
groups b | |
where (a.key1 = b.key2 OR a.key2 = b.key1) | |
and not cycle | |
) | |
select groups.key1, | |
dense_rank() OVER (order by min(groups.key2)) as bucket | |
from groups | |
group by groups.key1 | |
order by groups.key1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have made the world a better place.