2012-01-29 46 views
2

我想從另一個查詢中選擇一些數據。 的SQL看起來就像這樣:使用子查詢作爲軌道上的表3.1

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 

,但我有麻煩試圖翻譯成ActiveRecord的語言這一

我覺得我確定與子查詢

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

,但我不知道如何使用這個作爲「表」

回答

5

我直接去find_by_sql任何不平凡的東西:

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') 

Submission的類方法包裝,你應該沒問題。