首页 > 解决方案 > 如何在rails中的同一张表上获得具有不同where条件的列的总和?

问题描述

receipts我有从表中计算总收入的方法。但是目前sql每次调用方法都会调用两次,是否可以改进sql只调用一次数据库。raw sql如果需要,我很好。

  def total
    Receipt.where(receipt_type: 'income').sum(:amount) - Receipt.where(receipt_type: 'refund').sum(:amount)
  end

主要目标是避免两次数据库调用。如果可以仅在数据库中计算差异,那就更好了。谢谢。

标签: sqlpostgresqlrails-activerecord

解决方案


在 SQL 中,我会用

SELECT SUM(amount) FILTER (WHERE receipt_type = 'income')
       - SUM(amount) FILTER (WHERE receipt_type = 'refund')
FROM receipt

但我无法在红宝石中找到等价物。我没有这方面的经验,但从这个例子中,我认为以下应该有效:

Receipt.select("SUM(amount) FILTER (WHERE receipt_type = 'income') - SUM(amount) FILTER (WHERE receipt_type = 'refund') )

推荐阅读