Adriano Bacha
Adriano Bacha

Reputation: 1164

using subquery as a table on rails 3.1

I'm trying to select some data from another query. The SQL will look like this:

SELECT user_id, rank FROM 
(SELECT user_id, MAX(created_at) as latest_solution, COUNT(*) AS solved,
rank() OVER (ORDER by COUNT(*) desc) AS rank FROM submissions group by user_id) 
as leaderboard WHERE leaderboard.user_id = xx

but I'm having trouble trying to translate this into activerecord language

I think I'm doing ok with the following subquery:

Submission.select('user_id, MAX(created_at) as latest_solution, COUNT(*) as solved, rank() OVER (ORDER BY count(*) desc) as rank').group('user_id')

but I don't know how to use this as a "table".

Upvotes: 2

Views: 1378

Answers (1)

mu is too short
mu is too short

Reputation: 434685

I go straight to find_by_sql for anything non-trivial:

Submission.find_by_sql(%q{
    select user_id,
           rank
    from (
        select user_id,
               max(created_at) as latest_solution,
               count(*) AS solved,
               rank() over (order by count(*) desc) as rank
        from submissions
        group by user_id
    ) as leaderboard
    where leaderboard.user_id = :user_id
}, :user_id => 'xx')

Wrap that in a class method on Submission and you should be okay.

Upvotes: 5

Related Questions