【问题标题】:how can I group sum and count with sequel ORM and postgresl?如何使用 sql ORM 和 postgresql 对 sum 和 count 进行分组?
【发布时间】:2015-05-24 06:08:22
【问题描述】:

这对我来说太难了。这是给杰里米的!

我有两个表(虽然我也可以设想需要加入第三个表),我想在同一个表中汇总一个字段并计算行数,同时加入另一个表并以 json 格式返回结果。

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

这些表是带有项目名称和公司 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:

所以,第一个问题是为什么以及如何解决这个问题?

然后我想加入这两个表并从左侧(第一个表)中获取所有项目名称,并在第二个表中汇总金额和计数项目。我试过了

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 格式返回结果来实现这一点?

非常感谢,伙计们。

【问题讨论】:

    标签: ruby postgresql sequel


    【解决方案1】:

    想通了,我希望这对其他人有帮助:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2017-03-20
      • 2020-08-15
      • 2022-01-12
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      相关资源
      最近更新 更多