Skip to content

Instantly share code, notes, and snippets.

@wishdev
Created July 24, 2014 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wishdev/635f7a839877d79a6781 to your computer and use it in GitHub Desktop.
Save wishdev/635f7a839877d79a6781 to your computer and use it in GitHub Desktop.
Recursive grouping and bucket assignment
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;
@Gerardwx
Copy link

You have made the world a better place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment