Ruby 如何使用sequel ORM和postgresl进行分组求和和计数?

Ruby 如何使用sequel ORM和postgresl进行分组求和和计数?,ruby,postgresql,sequel,Ruby,Postgresql,Sequel,这对我来说太难了,伙计们。是给杰里米的 我有两个表(虽然我也可以设想需要连接第三个表),我希望在与另一个表连接的同时,对一个字段求和并计算表中的行数,并以json格式返回结果 首先,需要求和的数据类型字段是数字字段(10,2),数据作为params['amount']插入 这些表是包含项目名称和公司id的费用项目,以及包含公司id、项目和金额的费用项目(仅提及关键列)-“公司id”列已消除歧义 因此,以下代码: expense_items = DB[:expense_projects].left

这对我来说太难了,伙计们。是给杰里米的

我有两个表(虽然我也可以设想需要连接第三个表),我希望在与另一个表连接的同时,对一个字段求和并计算表中的行数,并以json格式返回结果

首先,需要求和的数据类型字段是数字字段(10,2),数据作为
params['amount']插入

这些表是包含项目名称和公司id的费用项目,以及包含公司id、项目和金额的费用项目(仅提及关键列)-“公司id”列已消除歧义

因此,以下代码:

expense_items = DB[:expense_projects].left_join(:expense_items, :expense_project_id => :project_id).where(:project_company_id => company_id).to_a.to_json
很好,但当我添加

expense_total = expense_items.sum(:amount).to_f.to_json
我收到一条错误消息,上面写着

TypeError - no implicit conversion of Symbol into Integer:
因此,第一个问题是为什么以及如何解决这个问题

然后我想连接这两个表,并从左侧(第一个表)获取所有项目名称,然后在第二个表中求和amount和count项。我试过了

DB[:expense_projects].left_join(:expense_items, :expense_items_company_id => expense_projects_company_id).count(:item).sum(:amount).to_json
这一切都失败了

我想要一个得到所有项目名称的结果(即使没有费用条目并返回如下内容):

project  item_count item_amount
pr 1      7           34.87
pr 2      0           0
如何通过一个查询以json格式返回结果来实现这一点


非常感谢,伙计们。

解决了这个问题,我希望这能帮助其他人:

DB[:expense_projects___p].where(:project_company_id=>user_company_id).
  left_join(:expense_items___i, :expense_project_id=>:project_id).
  select_group(:p__project_name).
  select_more{count(:i__item_id)}.
  select_more{sum(:i__amount)}.to_a.to_json