Ecto query with subquery contains group_by
Environment
- Elixir version (elixir -v): 1.6.4
- Database and version: PostgreSQL 9.5
- Ecto version (mix deps): 2.2.10
- Database adapter and version (mix deps): Postgrex 0.13.5
- Operating system: macOS High Sierra
Current behavior
#Ecto.Query<from b in PancakeV2.Business,
left_join: t in subquery(from t in PancakeV2.TrackingStatusStatistic,
where: t.tracking_status == "request_received",
group_by: [t.business_id],
select: %{business_id: t.business_id, tracking_count: fragment("COALESCE(?, 0)", sum(t.count))}),
on: b.id == t.business_id, where: ilike(b.name, ^"%%"),
order_by: [desc: fragment("COALESCE(?, 0)", t.tracking_count)], select: {b, t}>
[debug] QUERY OK source="businesses" db=34.3ms queue=0.1ms
SELECT count(DISTINCT b0."id") FROM "businesses" AS b0 LEFT OUTER JOIN (SELECT t0."business_id" AS "business_id", COALESCE(sum(t0."count"), 0) AS "tracking_count" FROM "tracking_status_statistics" AS t0 WHERE (t0."tracking_status" = 'request_received') GROUP BY t0."business_id") AS s1 ON b0."id" = s1."business_id" WHERE (b0."name" ILIKE $1) ["%%"]
[debug] QUERY ERROR source="businesses" db=5.8ms queue=0.3ms
SELECT b0."id" FROM "businesses" AS b0 LEFT OUTER JOIN (SELECT t0."business_id" AS "business_id", COALESCE(sum(t0."count"), 0) AS "tracking_count" FROM "tracking_status_statistics" AS t0 WHERE (t0."tracking_status" = 'request_received') GROUP BY t0."business_id") AS s1 ON b0."id" = s1."business_id" WHERE (b0."name" ILIKE $1) GROUP BY b0."id" ORDER BY COALESCE(s1."tracking_count", 0) DESC LIMIT $2 OFFSET $3 ["%%", 25, 0]
[info] Sent 500 in 177ms
** (exit) an exception was raised:
** (Postgrex.Error) ERROR 42803 (grouping_error): column "s1.tracking_count" must appear in the GROUP BY clause or be used in an aggregate function
(ecto) lib/ecto/adapters/sql.ex:431: Ecto.Adapters.SQL.execute_and_cache/7
(ecto) lib/ecto/repo/queryable.ex:133: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:37: Ecto.Repo.Queryable.all/4
(scrivener_ecto) lib/scrivener/paginater/ecto/query.ex:31: Scrivener.Paginater.Ecto.Query.entries/4
(scrivener_ecto) lib/scrivener/paginater/ecto/query.ex:15: Scrivener.Paginater.Ecto.Query.paginate/2
(pancake_v2) lib/pancake_v2_web/controllers/v1/snappy/business_controller.ex:97: PancakeV2Web.V1.Snappy.BusinessController.index/2
(pancake_v2) lib/pancake_v2_web/controllers/v1/snappy/business_controller.ex:1: PancakeV2Web.V1.Snappy.BusinessController.action/2
(pancake_v2) lib/pancake_v2_web/controllers/v1/snappy/business_controller.ex:1: PancakeV2Web.V1.Snappy.BusinessController.phoenix_controller_pipeline/2
(pancake_v2) lib/pancake_v2_web/endpoint.ex:1: PancakeV2Web.Endpoint.instrument/4
(phoenix) lib/phoenix/router.ex:278: Phoenix.Router.__call__/1
(pancake_v2) lib/pancake_v2_web/endpoint.ex:1: PancakeV2Web.Endpoint.plug_builder_call/2
(pancake_v2) lib/plug/debugger.ex:102: PancakeV2Web.Endpoint."call (overridable 3)"/2
(pancake_v2) lib/pancake_v2_web/endpoint.ex:1: PancakeV2Web.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:16: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) /app/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
Expected behavior
The query must be don't use group by after subquery cause bug like above. This ok when I'm using SQL query like this
SELECT * from businesses b LEFT JOIN (
SELECT tss.business_id, sum(tss."count") AS count FROM tracking_status_statistics tss
WHERE tss."date" >= '2018-07-18' AND tss."date" <= '2018-08-17' and tss.tracking_status = 'request_received'
GROUP BY tss.business_id
) AS s
ON b.id = s.business_id
ORDER BY COALESCE(s.count, 0) DESC
I am not sure if there is anything we can do from our side. It feels the best bet is to call exclude(:select) on the subquery so you don't include the tracking count.
Can you please try the exclude(:select) route and let us know how it goes?
But I need to select the tracking count from table TrackingStatusStatistic for my purpose
@sonhgc00016 oh, I see, you need to include it in the inner order by and in order to do that you need to be able to reference an aliased value. Can you try this: group_by: [t.business_id, fragment("tracking_count")]?
@josevalim if use group_by with tracking_count and t.business_id the result is not what I need. You can see the SQL query
SELECT * from businesses b LEFT JOIN (
SELECT tss.business_id, sum(tss."count") AS count FROM tracking_status_statistics tss
WHERE tss."date" >= '2018-07-18' AND tss."date" <= '2018-08-17' and tss.tracking_status = 'request_received'
GROUP BY tss.business_id
) AS s
ON b.id = s.business_id
ORDER BY COALESCE(s.count, 0) DESC
This SQL query return result as I expected but you see in ecto query
#Ecto.Query<from b in PancakeV2.Business,
left_join: t in subquery(from t in PancakeV2.TrackingStatusStatistic,
where: t.tracking_status == "request_received",
group_by: [t.business_id],
select: %{business_id: t.business_id, tracking_count: fragment("COALESCE(?, 0)", sum(t.count))}),
on: b.id == t.business_id, where: ilike(b.name, ^"%%"),
order_by: [desc: fragment("COALESCE(?, 0)", t.tracking_count)], select: {b, t}>
and the debug in console
[debug] QUERY OK source="businesses" db=34.3ms queue=0.1ms
SELECT count(DISTINCT b0."id") FROM "businesses" AS b0 LEFT OUTER JOIN (SELECT t0."business_id" AS "business_id", COALESCE(sum(t0."count"), 0) AS "tracking_count" FROM "tracking_status_statistics" AS t0 WHERE (t0."tracking_status" = 'request_received') GROUP BY t0."business_id") AS s1 ON b0."id" = s1."business_id" WHERE (b0."name" ILIKE $1) ["%%"]
[debug] QUERY ERROR source="businesses" db=5.8ms queue=0.3ms
SELECT b0."id" FROM "businesses" AS b0 LEFT OUTER JOIN (SELECT t0."business_id" AS "business_id", COALESCE(sum(t0."count"), 0) AS "tracking_count" FROM "tracking_status_statistics" AS t0 WHERE (t0."tracking_status" = 'request_received') GROUP BY t0."business_id") AS s1 ON b0."id" = s1."business_id" WHERE (b0."name" ILIKE $1) GROUP BY b0."id" ORDER BY COALESCE(s1."tracking_count", 0) DESC LIMIT $2 OFFSET $3 ["%%", 25, 0]
I donot need group by business_id on query, I want group by business_id in table TrackingStatusStatistic on subquery only.
@sonhgc00016 I think I see what you mean now. It is still a bit confusing though. Can you show how the query is being built and which repository information you are invoking? Because this query:
#Ecto.Query<from b in PancakeV2.Business,
left_join: t in subquery(from t in PancakeV2.TrackingStatusStatistic,
where: t.tracking_status == "request_received",
group_by: [t.business_id],
select: %{business_id: t.business_id, tracking_count: fragment("COALESCE(?, 0)", sum(t.count))}),
on: b.id == t.business_id, where: ilike(b.name, ^"%%"),
order_by: [desc: fragment("COALESCE(?, 0)", t.tracking_count)], select: {b, t}>
should not automatically add a group_by clause. If there is a group by clause, it is either because you are using distinct: true or calling a Repo operation that forces aggregation.
@josevalim this is my code, tell me what am I doing wrong?
query = from b in Business, where: ilike(b.name, ^text_search)
tracking_status_statistic = handle_date(params)
|> case do
nil -> from tss in TrackingStatusStatistic
{start_date, end_date} -> from tss in TrackingStatusStatistic, where: tss.date >= ^start_date and tss.date <= ^end_date
end
tracking_status_statistic = (
from tss in tracking_status_statistic,
where: tss.tracking_status == "request_received",
group_by: tss.business_id,
select: %{business_id: tss.business_id, tracking_count: fragment("COALESCE(?, 0)", sum(tss.count))}
)
query = (
from b in query,
left_join: tss in subquery(tracking_status_statistic),
on: b.id == tss.business_id
)
businesses_data = from [b, tss] in query, order_by: [desc: fragment("COALESCE(?, 0)", tss.tracking_count)], select: {b, tss}
|> Repo.paginate(page: params["page"] || 1, page_size: params["page_size"] || 25)
Could it be paginate that is adding the group_by? Ecto does not provide pagination, can you link to which repo you are using pls?
@josevalim I'm using https://github.com/drewolson/scrivener_ecto
It seems to be the bug in https://github.com/drewolson/scrivener_ecto. @josevalim do you have any suggestion?
Yes, the group_by is being added here: https://github.com/drewolson/scrivener_ecto/blob/master/lib/scrivener/paginater/ecto/query.ex#L52
They probably have a very good reason to add the group_by, so it is worth having a discussion there about why it is there and what could be done. Can you check if your query works if you do Repo.aggregate(query, :count)? Because if it does, maybe a solution is for them to use our aggregate(query, :count) instead of relying on a custom implementation.
Closing this for now as it is not an Ecto issue. :)