从每组中选择前15条记录
我想选择10个商户账户,为每个商户账户挑选前15条交易记录,页面大小如10*50?
我有这个查询,它给我提供了最多的记录,我需要修复来选择"每个商家帐户ID的前15条记录",而不仅仅是前150条记录。
欢迎任何指针、建议、代码修复!
SELECT * FROM (
SELECT account_id,transaction_id,ROWNUM RNUM
FROM transactions
WHERE status='P' AND ROWNUM < ( (p_page_number * p_page_size) + 1)
GROUP BY account_id,transaction_id, ROWNUM
ORDER BY account_id
) a
WHERE rnum >= ( ( (p_page_number - 1) * p_page_size) + 1);
解决方案
您可以使用DENSE_RANK()
窗口函数将组号分配给行,并使用ROW_NUMBER()
在每个组中分配序列号。然后,过滤就很容易了。
例如:
select *
from (
select
account_id,
transaction_id,
dense_rank() over(order by account_id) as g,
row_number() over(partition by account_id order by transaction_id) as rn
from transactions
where status = 'P'
) x
where g <= 10 -- the first 10 groups (accounts)
and rn <= 15 -- the first 15 transactions within each group
相关文章