分组依据和Rails 3

时间:2015-12-09 11:53:29

标签: ruby-on-rails activerecord

嗨我有一个有两列的表,例如表名是demo,列是id和百分比

    id      percentage
     1          50
     2          74
     1          66

现在我想按ID分组,然后取百分比的总和,然后根据某些条件选择记录,即小于40的百分比总和。

我有以下sql查询,它给了我正确的结果。

SELECT id ,(SELECT SUM("demo"."percentage")
AS sum_allocation_percentage FROM "demo" GROUP BY id)as 
sum_allocation_percentage from demo where sum_allocation_percentage < 100;

我需要将此查询放在rails 3中。

Demo.group('id')。sum(:percentage)

此后我该怎么办?

感谢。

1 个答案:

答案 0 :(得分:1)

嘿,您可以使用having子句作为

Demo.group('id').having("sum(percentage) < 100")