Skip to content

Instantly share code, notes, and snippets.

@codesnik
Created January 20, 2016 16:27
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 codesnik/54097d1ede74f819cf33 to your computer and use it in GitHub Desktop.
Save codesnik/54097d1ede74f819cf33 to your computer and use it in GitHub Desktop.
fetching postgresql data cubes with active record
def cube(relation, keys)
rs = relation.group("cube (#{keys.join(', ')})").pluck(*keys, 'count(*)', "grouping(#{keys.join(', ')})")
hs = {}
rs.group_by(&:pop).each do |grouping, rows|
hs[select_by_bitmask(grouping, keys)] =
rows.map do |*indexes, value|
[select_by_bitmask(grouping, indexes), value]
end.to_h
end
hs
end
private
def select_by_bitmask(bitmask, array);
result = []
array.reverse.each_with_index do |el, i|
result.push el if bitmask & 2**i == 0
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment