oracle 中的 Lead & LAG 聚合
Posted
技术标签:
【中文标题】oracle 中的 Lead & LAG 聚合【英文标题】:Aggregations on Lead & LAG in oracle 【发布时间】:2016-03-04 12:12:49 【问题描述】:这是关于甲骨文的 输入
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
结果应该有每次活动变化的总和
谢谢
【问题讨论】:
这不是问题,这是代码请求。 SO 不是代码编写服务。展示你的努力。 不是特定的编程!! 【参考方案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
【讨论】:
【参考方案2】: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 )
;
【讨论】:
【参考方案3】:您需要识别连续值的组。剩下的就是聚合。
一种方法是行数差法:
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);
【讨论】:
HI GORDON结果需求活动量订单100000914投注11.99999 1 100000914结算11.9999 2 100000914 BET 3 3 100000914结算3 4押卡活动金额100000914下注11.99999 100000914 BET 3 100000914结算3 100000914结算11.99999答案应该是这一点基于活动变化的方式ORDER BY CUSTID, MAX( FROMDT )
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 ) ;
@nkalis 。 . .如果区别在于输出中的顺序,那么您只需要适当的order by
子句。以上是关于oracle 中的 Lead & LAG 聚合的主要内容,如果未能解决你的问题,请参考以下文章