Skip to content

Instantly share code, notes, and snippets.

@danhawkins
Created March 20, 2022 00:14
Show Gist options
  • Save danhawkins/a3ef38578daed078a9f64f36989b7c7c to your computer and use it in GitHub Desktop.
Save danhawkins/a3ef38578daed078a9f64f36989b7c7c to your computer and use it in GitHub Desktop.
def list_groups(region \\ nil, search \\ nil) do
query =
from(g in Group)
|> filter_region(region)
|> add_rank(region)
query |> Repo.all()
end
# When no region is past we don't need to partition, we have global rank
defp add_rank(query, nil) do
from(g in query,
windows: [p: [partition_by: nil, order_by: [desc: g.score]]],
select_merge: %{group_rank: row_number() |> over(:p)}
)
end
# When a region is passed we should partition by the region to establish a rank in each region
defp add_rank(query, _region) do
from(g in query,
windows: [p: [partition_by: g.region, order_by: [desc: g.score]]],
select_merge: %{group_rank: row_number() |> over(:p)}
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment