【问题标题】:Rails 5, Postgesql and grouping by associationRails 5,Postgesql 和按关联分组
【发布时间】:2018-10-17 05:16:53
【问题描述】:

我很难理解 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,但是当我这样做时,输出不再按repetitions.repetition_index 分组。似乎它按trials.id 分组。

如何确保该组仅由 repetitions.repetition_index 提供?

更新

尝试:

@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|
-----

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-5


    【解决方案1】:

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

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

    如果您不想按trails.id 分组并希望按repetitions.repetition_index 分组,您必须从查询中仅选择repetitions.repetition_index,例如

    @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
      }
    

    【讨论】:

    • 谢谢维沙尔。明白这一切。但我还想在重复关联中包含另一列,称为:treatment_index。将其包含在组中似乎撤消了repetitions.repetition_index 分组,这就是我正在努力理解的内容。
    • 然后你必须与父表分组,在你的情况下,路径。我认为这不会影响您的结果。你试过了吗?
    • 如果我将 trial.id 包含在 group 方法中,这似乎也忽略了 repeats.repetition_index 组。
    • 你也可以使用数组的“uniq”方法,从查询中获取结果后
    • @DollarChills 尝试在组中添加trails.id, repetitions.repetition_index
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多