sql - 如何在rails中的同一张表上获得具有不同where条件的列的总和?
问题描述
receipts
我有从表中计算总收入的方法。但是目前sql
每次调用方法都会调用两次,是否可以改进sql
只调用一次数据库。raw sql
如果需要,我很好。
def total
Receipt.where(receipt_type: 'income').sum(:amount) - Receipt.where(receipt_type: 'refund').sum(:amount)
end
主要目标是避免两次数据库调用。如果可以仅在数据库中计算差异,那就更好了。谢谢。
解决方案
在 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') )
推荐阅读
- css - 位置粘性不适用于 body{overflow-x: hidden; }
- html - div大小不起作用
- node.js - 如果用户不存在,则 MongoDB 更新
- javascript - 在 Android WebView 中禁用 console.assert
- python - MySQL-python 安装后报错
- neo4j - 如何使用 Cypher 查找两个节点之间的中间节点
- python - 如何从负值元组列表中打印绝对值?
- ruby-on-rails - 从列表中添加选项作为标签
- circleci - 使用 AWS CodePipeline 或其他的复杂/编排 CD
- android - Firebase Network Dispatcher 在应用关闭后停止工作。但是 GCM 网络管理器非常适合上述场景