oracle 中 Lead 和 LAG 的聚合

Aggregations on Lead & LAG in oracle

这是关于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

结果应该有每个 activity 变化的金额总和

谢谢

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

一种方法是行数差法:

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);
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
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 )
;