【问题标题】:elixir ecto - the right way to get an avarage score from a columnelixir ecto - 从列中获得平均分数的正确方法
【发布时间】:2022-01-13 11:42:09
【问题描述】:

从列中获取平均数的正确方法是什么? 我有这个问题:

q = from r in Review,
      where: r.module_id == ^module_id,
      where: r.delete == false,
      select: %{entries: r, stars: avg(r.stars)}

    r = Repo.all(q)

总是会出现这个错误:

(grouping_error) 列“r0.id”必须出现在 GROUP BY 子句中或 在聚合函数中使用

这是什么意思以及如何解决?

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

    无法选择具有不同维度的结果。当avg 汇总不同的评论时,您期望在entries 中获得什么?

    考虑以下输入:

    | id | module_id | stars |
    |----|-----------|-------| 
    |  1 |     1     |   3   |
    |  2 |     1     |   5   |
    |  3 |     2     |   1   |
    

    好的,对于module_id == 1avg(stars) 将是4。但是r 应该是什么呢?

    也就是说,您可能应该重新考虑查询本身。

    q =
      from r in Review,
      where: r.delete == false,
      where: r.module_id == ^module_id,
      group: r.module_id,
      select: %{module: r.module_id, stars: avg(r.stars)}
    

    或喜欢,取决于您的实际需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多