从每个组中选择前15条记录

问题描述 投票:0回答:1

我想选择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);
sql oracle filtering greatest-n-per-group paging
1个回答
0
投票

这将为您提供“每个商人帐户ID的前15条记录”:

SELECT *
FROM (
  SELECT 
    account_id, 
    transaction_id, 
    ROW_NUMBER() OVER(
      PARTITION BY account_id -- Break into groups of merchants
      ORDER BY transaction_id -- Assign row number based on transaction, within merchants
    ) RowNum
  FROM transactions
  WHERE status='P'
) src
WHERE src.RowNum <= 15
ORDER BY account_id, transaction_id

我不确定您的p_page_number, p_page_size, and ROWNUM参数如何发挥作用。


0
投票

您可以使用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
) x
where g <= 10 -- the first 10 groups (accounts)
  and rn <= 15 -- the first 15 transactions within each group
© www.soinside.com 2019 - 2024. All rights reserved.