I want to group by region. So I was getting this error:
(Postgrex.Error) ERROR 42803 (grouping_error) column “l0.id” must appear in the GROUP BY clause or be used in an aggregate function
I have a table with a column called “locations” and I want to query and group by country_region
id | country_region | details
510 Alegeria | ...
499 Australia | ...
470 Australia | ...
472 Australia | ...
487 Australia | ...
So I wrote this:
def grouped_by_region() do
Location
|> group_by([e], e.country_region)
|> select([e], %{region: e.country_region, count: count(e.id), items: fragment("ARRAY_AGG(?)", e.id)})
|> order_by([e], asc: e.country_region)
end
And now I get this:
[
%{region: "Algeria", count: 1, items: [510]},
%{region: "Australia", count: 5, items: [499, 470, 471, 472, 487]},
]
QUESTION
I do not want items:[49,470,471]
to contain the ids. I want items:
to contain the actual records. So something similar to this:
[
%{region: "Algeria", count: 1, items: [%Location{id: 510 ...} ...],
%{region: "Australia", count: 5, items: [%Location{id: 499}, %Location{id: 470} ... ],
]
I have tried the following fragments.
fragment("ARRAY_AGG(?)", e.id) # returns a lit of ids
fragment("ARRAY_AGG(?)", e) # error
fragment("ARRAY_AGG(?)", [e]) # error
fragment("ARRAY_AGG(?)", {e}) # error
How do I fix the query? Thanks.