1

我有一个表来存储用户的所有能力,所以我想要查询的是每天使用 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
4

1 回答 1

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

于 2013-09-29T13:56:00.057 回答