代码之家  ›  专栏  ›  技术社区  ›  DollarChills

Rails 5、Postgesql和按关联分组

  •  0
  • DollarChills  · 技术社区  · 7 年前

    我正在努力让我的头周围Postgesql和分组协会。

    我有一个反复多次的试验。我想按列重复分组,以便在变量中使用。目前我有:

    @trials = Trial.joins(:repetitions).group('repetitions.repetition_index')
    

    PG::GroupingError: ERROR:  column "trials.id" must appear in the GROUP BY clause or be used in an aggregate function
    

    现在从阅读这个我需要包括 trials.id 在我的group方法中,但是当我这样做时,输出不是按 repetitions.repetition_index 试验id .

    重复。重复指数 ?

    尝试:

    @trials = Trial.joins(:repetitions).select('repetitions.repetition_index,repetitions.treatment_index').group('trials.id, repetitions.repetition_index,repetitions.treatment_index')
    

    <% @trials.each do |r| %>
        <table class="table table-bordered">
            <tr>
                <td><%= r.repetition_index %></td>
                <td><%= r.treatment_index %></td>
            </tr>
        </table>
    <% end %>
    

    给我一个输出:

    |1|1|
    -----
    |1|2|
    -----
    |2|1|
    -----
    |2|2|
    -----
    

    | |1|
    |1|2|
    -----
    | |1|
    |2|2|
    -----
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Vishal    7 年前

    如果你想摆脱这个错误,你可以这样做

    @trials = Trial.joins(:repetitions).group('trials.id, repetitions.repetition_index')
    

    trails.id 你想分组吗 repetitions.repetition_index 只能从查询中选择repetitions.repetition\u索引

    @trials = Trial.joins(:repetitions).select('repetitions.repetition_index').group('repetitions.repetition_index')
    

    更新 根据你最新的问题,我认为你需要下面这样的东西。未测试查询。如果不起作用就告诉我

     Trial.
     joins(:repetitions).
     select('repetitions.repetition_index,repetitions.treatment_index').
     group_by {
        |repetition| repetitions.repetition_index
      }