我需要从我的表中获取3个金额字段中最大的一个。但是在名为expense_amt and income_amt的事务表中有两个金额字段。我需要得到3个最大的金额字段通过查看这两个领域。我知道我可以使用多个字段进行查询,比如
Model.order('expense_amt', 'income_amt').limit(3)但这并没有像我预期的那样返回3个金额字段中的最大值。所以基本上我需要检索3个事务中最大的一个。这就像是
Transactions
id expense_amt income_amt transaction_type
1 100 NULL 1
2 200 NULL 3
3 NULL 400 1
4 NULL 800 2
5 1000 NULL 1
So the output of largest 3 would be [1000, 800, 400] 发布于 2015-10-06 15:03:36
这不是最好的解决方案,但也许您可以从这里入手:)
如果这两个值不一致,则和将始终是最高值。使用COALESCE SQL函数,我们用0替换NULL以使计算工作。
Model.select("(COALESCE(expense_amt, 0) + COALESCE(income_amt, 0)) AS combined_amt").
order("combined_amt DESC").
limit(3).
map{|row| row["combined_amt"]}发布于 2015-10-06 12:04:08
我已经编辑了这个解决方案
expense= Model.order('expense_amt DESC').limit(3).map{|exp| exp.expense_amt}
income = Model.order('income_amt DESC').limit(3).map{|inc| inc.income_amt}
result= expense +income
result.sort{|a,b| b <=> a}.first(3)https://stackoverflow.com/questions/32961299
复制相似问题