Using fragment & group_by together with postgres & ecto?

假如想象 提交于 2021-01-28 09:33:49

问题


I'm struggling to get this to work with Postgres and Ecto. The query below works fine without the group_by, but I need to group on the fragment field, which it can't seem to see. Any idea what's wrong with it?

  def query_clicks do
    from(Click)
    |> select(
      [c],
      [
        fragment("date_trunc('hour',?) as hour", c.inserted_at), c.link_id]
      )
    |> group_by([c], c.hour)
    |> Repo.all
  end

Result:

iex(1)> recompile; Shortr.LinkContext.query_clicks
[debug] QUERY ERROR source="clicks" db=1.2ms queue=4.9ms
SELECT date_trunc('hour',c0."inserted_at") as hour, c0."link_id" FROM "clicks" AS c0 GROUP BY c0."hour" []
** (Postgrex.Error) ERROR 42703 (undefined_column) column c0.hour does not exist

    query: SELECT date_trunc('hour',c0."inserted_at") as hour, c0."link_id" FROM "clicks" AS c0 GROUP BY c0."hour"
    (ecto_sql) lib/ecto/adapters/sql.ex:604: Ecto.Adapters.SQL.raise_sql_call_error/1
    (ecto_sql) lib/ecto/adapters/sql.ex:537: Ecto.Adapters.SQL.execute/5
    (ecto) lib/ecto/repo/queryable.ex:147: Ecto.Repo.Queryable.execute/4
    (ecto) lib/ecto/repo/queryable.ex:18: Ecto.Repo.Queryable.all/3
iex(1)> 

回答1:


In the resulting SQL you call c0.hour whereas you alias the column to hour. It should be

SELECT date_trunc('hour',c0."inserted_at") as hour, c0."link_id" FROM "clicks" AS c0 GROUP BY hour

In Ecto this would become

def query_clicks do
  from(Click)
  |> select(
    [c],
    [
      fragment("date_trunc('hour',?) as hour", c.inserted_at), c.link_id
    ]
  )
  |> group_by([c], fragment("hour"))
  |> Repo.all
end

Another issue is the link_id, any field in the SELECT clause must appear in the GROUP BY clause or be an aggregrate. You could for example also group by link_id.



来源:https://stackoverflow.com/questions/54494557/using-fragment-group-by-together-with-postgres-ecto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!