Jak S
Jak S

Reputation: 669

How to use an aggregate in an order by in DataMapper?

I've got a simple class like:

class Foo
    include DataMapper::Resource
    property :id, Serial
    property :bar, Text, lazy: false
    property :created_on, DateTime, default: lambda { |r,p| DateTime.now }
end

I want to select them, grouped by bar and ordered by max(created_on). The SQL I need is:

SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY MAX("created_on") DESC

but I don't know how to get this with DataMapper.

I've tried something like:

Foo.all(fields: [:bar], unique: true, order: [:created_on.desc.max])

but you can't use max like that. I can't find out how to do it.

Can you help?

Upvotes: 2

Views: 286

Answers (1)

colevoss
colevoss

Reputation: 46

It seems as if using the max aggregate is not necessary. By ordering in descending order of the created_on column its going to find the MAX and go from there.

You could probably get away with:

Foo.all(fields: [:bar], unique: true, order: [created_on.desc])

without using .max in the order.

This would be same as:

SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY "created_on" DESC

Hope this works.

Also take a look at http://datamapper.org/docs/find.html

Upvotes: 1

Related Questions