如何从db查询每天最多2条随机记录?

时间:2013-09-29 12:19:21

标签: sql ruby-on-rails postgresql activerecord

我有一个表来存储用户的所有能力,所以我想要查询的是每天使用ActiveRecord或Postgresql中的原始sql获取最多2个随机记录的列表?

id   use_id   available_date
----------------------------
1    1        2013-01-01
2    1        2013-01-02
3    1        2013-01-03
4    2        2013-01-01
5    2        2013-01-02
6    3        2013-01-01
7    3        2013-01-03

预期输出散列或sql记录:

{
  "2013-01-01": [1, 2], # random top 2 user_ids, it also could be [1, 3], or [2, 3]
  "2013-01-02": [1, 2],
  "2013-01-03": [1, 3]
}

id   use_id   available_date
----------------------------
1    1        2013-01-01
4    2        2013-01-01
2    1        2013-01-02
5    2        2013-01-02
3    1        2013-01-03
7    3        2013-01-03

1 个答案:

答案 0 :(得分:0)

您可以使用row_number()窗口函数:

with cte as (
     select
         available_date, use_id,
         row_number() over(partition by available_date order by random()) as rn
     from Table1
)
select
    available_date, array_agg(use_id) 
from cte
where rn <= 2
group by available_date

<强> sql fiddle demo