Search code examples
sqloracle-databaseoracle11glag

Oracle SQL find row crossing limit


I have a table which has four columns as below

  1. ID.
  2. SUB_ID. one ID will have multiple SUB_IDs
  3. Revenue
  4. PAY where values of Pay is always less than or equal to Revenue

select * from Table A order by ID , SUB_ID will have data as below

ID   SUB_ID  REVENUE    PAY
100   1      10          8
100   2      12          9
100   3       9          7
100   4      11         11
101   1       6          5
101   2       4          4
101   3       3          2
101   4       8          7
101   5       4          3
101   6       3          3

I have constant LIMIT value 20 . Now I need to find the SUB_ID which Revenue crosses the LIMIT when doing consecutive SUM using SUB_ID(increasing order) for each ID and then find total Pay ##. In this example

  1. for ID 100 Limit is crossed by SUB ID 2 (10+12) . So total Pay is 17 (8+9)
  2. for ID 101 Limit is crossed by SUB ID 4 (6+4+3+8) . So total Pay is 18 (5+4+2+7)

Basically I need to find the row which crosses the Limit.


Solution

  • Fiddle: http://sqlfiddle.com/#!4/4f12a/4/0

    with sub as
     (select x.*,
             sum(revenue) over(partition by id order by sub_id) as run_rev,
             sum(pay) over(partition by id order by sub_id) as run_pay
        from tbl x)
    select *
      from sub s
     where s.run_rev = (select min(x.run_rev)
                          from sub x
                         where x.id = s.id
                           and x.run_rev > 20);