Select: How to return a map while using aggregates functions

I like to return a query result as a list of maps for easier handling later on.

For normal selects I can use something like this (Taken from Ecto.Query — Ecto v3.10.3):

City |> select([c], map(c, [:name]))

But what about if I have a select with aggregate functions?

      Payment
      |> where([p], p.customer_id == ^options[:customer_id])
      |> select([p], [
          count(),
          sum(p.payment_in_cents),
          selected_as( fragment(...
      [...]

And the result set should look like [ {count: 100, sum: 5000, ...}, ...]

Can this be done at all?
Sorry, I’m lost at the moment

Found a solution…
Using the example shown in the very next line:

      Payment
      |> where([c], c.customer_id == ^options[:customer_id])
      |> select([c], %{
        count: count(),
        sum: sum(c.payment_in_cents),
        bucket: selected_as( [...]

gives

[
  %{count: 2, sum: 200, bucket: 5},
  %{count: 2, sum: 205, bucket: 7},
  %{count: 2, sum: 200, bucket: 9}
]
1 Like