Select 每组前 15 条记录
Select top 15 records from each group
我想select10个商家账户,为每个商家账户选择前15条交易记录,页面大小为10*50?
我有这个查询,它为我提供了最高记录,我需要修复以选择 "top 15 records for each merchant account id" 而不仅仅是前 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);
这会给你"top 15 records for each merchant account id":
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
参数是如何发挥作用的。
您可以使用 DENSE_RANK()
window 函数为行分配组号,并使用 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
我想select10个商家账户,为每个商家账户选择前15条交易记录,页面大小为10*50?
我有这个查询,它为我提供了最高记录,我需要修复以选择 "top 15 records for each merchant account id" 而不仅仅是前 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);
这会给你"top 15 records for each merchant account id":
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
参数是如何发挥作用的。
您可以使用 DENSE_RANK()
window 函数为行分配组号,并使用 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