1

I want to select 10 merchant accounts, pick top 15 transaction records for each merchant account with page size like 10*50 ?

I have this query which gives me the top records, where I need a fix to pick the "top 15 records for each merchant account id" and not just the top 150 records.

Any pointers, suggestions, code fixes are welcome !

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);
Balaji Birajdar
  • 2,394
  • 1
  • 23
  • 29
  • 1
    Thanks Balaji Birajdar. I wondered what version of the database are you using? – alexgibbs Oct 07 '19 at 18:08
  • 1
    Lookup cross apply and `fetch first 15 rows only`.. https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9530807800346558418 – xQbert Oct 07 '19 at 19:21
  • 1
    What 15 transactions? How do you want them ordered the most recent? the oldest? based on transaction_ID? – xQbert Oct 07 '19 at 20:02

2 Answers2

2

You can use the DENSE_RANK() window function to assign group numbers to rows, and ROW_NUMBER() to assign a serial number within each group. Then, filtering is easy.

For example:

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
The Impaler
  • 45,731
  • 9
  • 39
  • 76
1

This will give you the "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

I'm not quite sure as to how your p_page_number, p_page_size, and ROWNUM parameters come into play.

ravioli
  • 3,749
  • 3
  • 14
  • 28