2013-09-29 118 views
1

我有一個表來存儲用戶的所有能力,所以我想要查詢的是每天使用ActiveRecord或Postgresql中的原始sql獲取最多2個隨機記錄的列表?如何從db每天查詢最大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 
+2

你能不能給一個例子多輸出並解釋它? –

+0

@IgorRomanchenko我添加了示例輸出。 – Samnang

回答

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