Ruby Join Query Group by Sum特殊值

时间:2014-04-02 06:59:38

标签: ruby-on-rails ruby ruby-on-rails-3

@rentschedule_cc = 
    RentSchedule.joins([{:rent => {:lease => :lease_rent_rolls}}, :charge_code])
                .where("lease_rent_rolls.id = 453861 and
                        rent_schedules.from_date < '#{Date.today.strftime("%Y-%m-%d %H:%M:%s")}' and 
                        rent_schedules.to_date > '#{Date.today.strftime("%Y-%m-%d %H:%M:%s")}' and 
                        rent_schedules.charge_code_id IS NOT NULL")
                .group("charge_codes.charge_type")

我正在获取分组中的第一条记录,但我想要sum(rent_schedules.annual_psf)sum(rent_schedules.monthly_amt)。如何在此查询中获取总和值?

1 个答案:

答案 0 :(得分:0)

您可以在选择

中写入总和
@rentschedule_cc = 
    RentSchedule.joins([{:rent => {:lease => :lease_rent_rolls}}, :charge_code])
            .where("lease_rent_rolls.id = 453861 and
                    rent_schedules.from_date < '#{Date.today.strftime("%Y-%m-%d %H:%M:%s")}' and 
                    rent_schedules.to_date > '#{Date.today.strftime("%Y-%m-%d %H:%M:%s")}' and 
                    rent_schedules.charge_code_id IS NOT NULL")
            .group("charge_codes.charge_type")
            .select("rent_schedules.*, sum(rent_schedules.annual_psf) as sum1, sum(rent_schedules.monthly_amt) as sum2")

并获取结果

中的sum1sum2