关于铅和铅的汇总LAG在甲骨文

时间:2016-03-04 12:12:50

标签: sql oracle window-functions

这是关于oracle的 输入

CUSTID          FROMDT         ACTIVITY     NEXTDATE
100000914   31/01/2015 14:23:51 Bet         3.999996
100000914   31/01/2015 14:29:07 Bet         3.999996
100000914   31/01/2015 14:32:59 Bet         2
100000914   31/01/2015 14:35:35 Bet         1.999998
100000914   31/01/2015 16:52:32 Settlement  3.999996
100000914   31/01/2015 16:54:39 Settlement  1.999998
100000914   31/01/2015 16:55:04 Settlement  2
100000914   31/01/2015 16:57:00 Settlement  3.999996
100000914   31/01/2015 16:57:10 Bet         3
100000914   31/01/2015 19:21:15 Settlement  3

结果

CUSTID      ACTIVITY    AMOUNT      
100000914   Bet         11.99999    
100000914   Settlement  11.99999    
100000914   Bet          3          
100000914   Settlement   3

结果应该包含每次活动变更的金额总和

由于

3 个答案:

答案 0 :(得分:1)

SELECT CUSTID,
       ACTIVITY,
       total - LAG( total, 1, 0 ) OVER ( PARTITION BY CUSTID ORDER BY FROMDT ) AS total
FROM   (
  SELECT CUSTID,
         FROMDT,
         ACTIVITY,
         SUM( NEXTDATE ) OVER ( PARTITION BY CUSTID ORDER BY FROMDT ) AS total,
         CASE ACTIVITY
              WHEN LEAD( ACTIVITY ) OVER ( PARTITION BY CUSTID ORDER BY FROMDT )
              THEN 0
              ELSE 1
              END AS has_changed
  FROM   your_table
)
WHERE  has_changed = 1;

<强>输出

CUSTID    ACTIVITY   TOTAL
--------- ---------- --------
100000914 Bet        11.99999
100000914 Settlement 11.99999
100000914 Bet               3
100000914 Settlement        3

答案 1 :(得分:0)

您需要识别连续值组。剩下的就是聚合。

一种方法是行数方法的差异:

select custid, activity, sum(amount)
from (select t.*,
             (row_number() over (partition by custid order by fromdt) -
              row_number() over (partition by custid, activity order by fromdt)
             ) as grp
      from t
     ) t
group by custid, grp, activity
order by custid, max(fromdt);

答案 2 :(得分:0)

select custid, activity, sum(amount)
from (select jg_dig_test.*,
             (row_number() over (partition by custid order by fromdate) - row_number() over (partition by custid, activity order by fromdate)
             ) as grp
      from jg_dig_test
     ) jg_dig_test
group by custid, grp, activity
ORDER BY CUSTID, MAX( FROMDaTe )
;