我有一个简单的类:
class Foo
include DataMapper::Resource
property :id, Serial
property :bar, Text, lazy: false
property :created_on, DateTime, default: lambda { |r,p| DateTime.now }
end
我想选择它们,按 bar 分组并按 max(created_on) 排序。我需要的 SQL 是:
SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY MAX("created_on") DESC
但我不知道如何使用 DataMapper 获取它。
我试过类似的方法:
Foo.all(fields: [:bar], unique: true, order: [:created_on.desc.max])
但是你不能那样使用 max。我不知道该怎么做。
你能帮忙吗?
最佳答案
似乎没有必要使用最大聚合。通过按 created_on 列的降序排序,它将找到 MAX 并从那里开始。
你可能会逃脱:
Foo.all(fields: [:bar], unique: true, order: [created_on.desc])
不在订单中使用 .max。
这与:
SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY "created_on" DESC
希望这能奏效。
关于ruby - 如何在 DataMapper 中按顺序使用聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754858/