如何运行 group() 和 sum() 查询并返回的不仅仅是总和以及用于在活动记录中分组的列

问题描述 投票:0回答:1

我有 2 个表,类别(名称,图像数据)和费用(名称,金额,日期)通过 has_and_belongs_to_many 相关(费用有很多类别,类别有很多费用)。我想编写一个活动记录查询,它将选择所有类别及其相关费用,并按类别 id 对它们进行分组,并返回类别表中的其他列(名称和图像数据)

我已经尝试过了

1.

Category.includes(:expenses).group('categories.id').sum(:amount)

但我得到的是

{4=>0.75e5, 6=>0.18e6, 5=>0.0}

这不会返回类别表中的列

2.

k = Category.includes(:expenses).group('categories.id').select('categories.*, SUM(expenses.amount) AS total_amount').pluck('categories.id', 'categories.name', 'total_amount')

但我收到列名“total_amount”未知的错误。

3. 我还尝试根据我想要返回的类别表的所有列对结果进行分组,但我认为这样做会使查询变慢。

Category.includes(:expenses).group('id', 'name', 'image_data').sum(:amount)
ruby-on-rails ruby activerecord
1个回答
0
投票

您必须包含分组中返回的任何列,因此您的第三个选项应该有效。这就是 SQL 中聚合的工作原理,当您进行分组和计数/求和时,每个分组列只有一行,因此无法包含其他非分组列。

© www.soinside.com 2019 - 2024. All rights reserved.