1

Please help me t make below select query

Source table

name Amount  
 -----------
 A   2    
 B   3    
 C   2
 D   7

if limit is 5 then result table should be

name Amount  
 -----------
 A   2    
 B   3   

if limit is 8 then result table

name Amount  
 -----------
 A   2    
 B   3    
 C   2
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Manu
  • 89
  • 1
  • 9

1 Answers1

4

You can use window function to achieve this:

select name,
    amount
from (
    select t.*,
        sum(amount) over (
            order by name
            ) s
    from your_table t
    ) t
where s <= 8;

The analytic function sum will be aggregated row-by-row based on the given order order by name.

Once you found sum till given row using this, you can filter the result using a simple where clause to find rows till which sum of amount is under or equal to the given limit.


More on this topic:

Community
  • 1
  • 1
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76