左外连接的SUM顺序

时间:2019-07-21 18:43:48

标签: sql postgresql activerecord

我有一个Rails应用,并且正在使用诸如此类的作用域:

group('"expenditures"."id"').order('SUM("expenditure_items"."amount") ' +  direction)

在此之前有一个external_left_join(:expenditure_items)。问题是,当没有expense_items时,SUM首先对其他非零和项进行排序。看起来像这样:

  • 总和
  • $ 100
  • $ 200
  • $ 300
  • $ 0
  • $ 0
  • $ 0

我要先买$ 0的商品。

1 个答案:

答案 0 :(得分:2)

您可以使用COALESCE

group('"expenditures"."id"').order('COALESCE(SUM("expenditure_items"."amount"),0) '+ direction)

NULLS FIRST/LAST子句:

SUM("expenditure_items"."amount")  NULLS FIRST
相关问题