每个组的Rails LIMIT

时间:2012-10-18 14:49:52

标签: ruby-on-rails postgresql activerecord ruby-on-rails-3.2

我试图将每个类别的记录限制为5,但我最终只返回了5条记录。

如何在Rails ActiveRecord中翻译此sql语句?

SELECT *
FROM "jobs" a
WHERE (
  SELECT COUNT(*)
  FROM jobs
  WHERE ID = a.ID
) <= 5
AND jobkey_confirmation IS NOT NULL
AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())

我只能执行以下操作,如上所述仅返回5条记录:

scope :confirmed_this_month, where("jobkey_confirmation IS NOT NULL AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())").group("category").limit(5).order("created_at DESC")

2 个答案:

答案 0 :(得分:1)

你能使用find_by_sql吗?

Job.find_by_sql('SELECT * FROM "jobs" a WHERE (SELECT COUNT(*) FROM jobs WHERE ID = a.ID ) <= 5 AND jobkey_confirmation IS NOT NULL AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now()))

或者您是否希望完全用AR Calls取而代之?

- 从评论中提取代码----

def self.limited_grouped_jobs 
    find_by_sql("SELECT * FROM jobs a WHERE (SELECT COUNT(*) FROM jobs WHERE ID = a.ID ) <= 5 AND jobkey_confirmation IS NOT NULL AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())")
end

答案 1 :(得分:1)

select j.*
from
    jobs j
    inner join (
        select
            row_number() over (partition by category_id order by id) rn,
            id
        from jobs
        where
            jobkey_confirmation IS NOT NULL
            AND EXTRACT(MONTH from created_at) = EXTRACT(MONTH from now())
    ) i on i.id = j.id
where rn <= 5