0

我的开发环境(SQLite)中有一个功能方法,看起来像这样:

def self.ytd
Production.find(
    :all,
    conditions: ["year == ?", Time.now.year],
    select: "carrier_id, amount, SUM(amount) as sum_amount",
    group: :carrier_id
    )
end

此方法成功搜索由:carrier_id:amount列组成的表。:amount然后它根据分组对列求和:carrier_id

我正在尝试使用 Postgresql 转换为生产环境。下面的代码成功地对记录进行分组,但是我无法对:amount. 我曾尝试修改.sum("productions.amount")该方法但没有成功。我相信有一个简单的解决方案,但它暗示我..有人可以帮忙吗?谢谢

def self.ytd
Production.select("DISTINCT ON (productions.carrier_id) productions.carrier_id, productions.amount ")
               .where("productions.year = (?)", "#{Time.now.year}")
               .group("productions.amount, productions.carrier_id, productions.id")
end
4

1 回答 1

2

Removed DISTINCT ON, addedSUM(amount) as sum_amount和 grouped on:carrier_id产生了预期的结果。

def self.ytd
Production.select("productions.carrier_id, SUM(amount) as sum_amount")
               .where("productions.year = (?)", "#{Time.now.year}")
               .group("productions.carrier_id")      
end
于 2013-03-26T03:08:01.880 回答