将fragment&group_by与postgres和ecto一起使用?

时间:2019-02-02 15:35:42

标签: elixir phoenix-framework ecto

我努力让这与Postgres的和外生的工作。下面的查询在没有group_by的情况下可以正常工作,但是我需要对似乎看不到的fragment字段进行分组。知道有什么问题吗?

  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

结果:

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 个答案:

答案 0 :(得分:1)

在生成的SQL中,您调用maybe,而将列别名为c0.hour。应该是

hour

在Ecto中,这将变成

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

另一个问题是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 ,SELECT子句中的任何字段都必须出现在GROUP BY子句中或为聚集体。例如,您还可以按link_id分组。