Bala
Bala

Reputation: 21

Oracle analytical function

I have similar problem. Can you anyone give me solution. Below is the table value

    10    
    20    
    30   
    40

I want output like this

10  10-2     8    
20  20-8    12    
30  30-12   18    
40  40-18   22   

Sort by ascending and always substract 2 for the first recrod and use the result for the subsequent records.

Upvotes: 2

Views: 82

Answers (2)

Ponder Stibbons
Ponder Stibbons

Reputation: 14848

For completness - basic, recursive solution:

SQLFiddle

with t(val, n) as (
  select val, val-2 from test where val = 10
  union all select test.val, test.val-n from test, t where test.val = t.val + 10 )
select * from t

Upvotes: 0

MT0
MT0

Reputation: 167972

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE TEST ( VAL ) AS
          SELECT 10 FROM DUAL
UNION ALL SELECT 20 FROM DUAL
UNION ALL SELECT 30 FROM DUAL
UNION ALL SELECT 40 FROM DUAL;

Query 1:

WITH Parities AS (
  SELECT VAL,
         MOD( ROW_NUMBER() OVER ( ORDER BY VAL ), 2 ) AS Parity
  FROM   TEST
)
SELECT VAL,
       ABS( SUM( CASE PARITY WHEN 1 THEN -VAL ELSE VAL END ) OVER ( ORDER BY VAL ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) + 2 ) AS total
FROM   Parities

Results:

| VAL | TOTAL |
|-----|-------|
|  10 |     8 |
|  20 |    12 |
|  30 |    18 |
|  40 |    22 |

Upvotes: 6

Related Questions