我有一个Rails应用,并且正在使用诸如此类的作用域:
group('"expenditures"."id"').order('SUM("expenditure_items"."amount") ' + direction)
在此之前有一个external_left_join(:expenditure_items)。问题是,当没有expense_items时,SUM首先对其他非零和项进行排序。看起来像这样:
我要先买$ 0的商品。
答案 0 :(得分:2)
您可以使用COALESCE
:
group('"expenditures"."id"').order('COALESCE(SUM("expenditure_items"."amount"),0) '+ direction)
或NULLS FIRST/LAST
子句:
SUM("expenditure_items"."amount") NULLS FIRST