[英]How to query max 2 random records by each day from db?
I have a table to store all abilities of users, so what I want the query does is to get a list of max 2 random records by each day using either ActiveRecord or raw sql in Postgresql? 我有一个表来存储用户的所有功能,所以我要查询的是每天使用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
Expected output either a hash or sql records: 预期输出是哈希或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
You can use row_number() window function: 您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.