Oracle分析功能

时间:2015-06-30 11:39:44

标签: oracle function analytical

我有类似的问题。你能有人给我解决方案吗? 以下是表值

    10    
    20    
    30   
    40

我想要这样的输出

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

按升序排序,并为第一个recrod总是减去2,并将结果用于后续记录。

2 个答案:

答案 0 :(得分:6)

SQL Fiddle

Oracle 11g R2架构设置

console.log(this.toString());

查询1

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;

<强> Results

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

答案 1 :(得分:0)

对于完整性 - 基本的,递归的解决方案:

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