Oracle Study Notes: MoM calculation

First, build a test table

-- 创建表
create table temp_cwh_test
(
    date_time date,
    cnt number
);
-- 插入测试数据
insert into temp_cwh_test values (to_date('2019-01-05','yyyy-mm-dd'), 25);
insert into temp_cwh_test values (to_date('2019-02-05','yyyy-mm-dd'), 20);
insert into temp_cwh_test values (to_date('2019-03-05','yyyy-mm-dd'), 63);
insert into temp_cwh_test values (to_date('2019-04-05','yyyy-mm-dd'), 96);
insert into temp_cwh_test values (to_date('2019-05-05','yyyy-mm-dd'), 25);
insert into temp_cwh_test values (to_date('2019-07-05','yyyy-mm-dd'), 12);
insert into temp_cwh_test values (to_date('2019-08-05','yyyy-mm-dd'), 39);
insert into temp_cwh_test values (to_date('2019-09-05','yyyy-mm-dd'), 250);
insert into temp_cwh_test values (to_date('2019-11-05','yyyy-mm-dd'), 1);
insert into temp_cwh_test values (to_date('2019-12-05','yyyy-mm-dd'), 525);

Second, the chain is calculated

  • concept

MoM = (n-month - the n- month) / the n- January * 100%

An = (n May this year - last year, the first month n) / n May of last year * 100%

  • Compute

Due to the missing part of the data, some months without data, this time can construct a base table.

select '2019-' || lpad(rownum, 2, '0') as col from dual connect by level <= 12;
/*
2019-01
2019-02
2019-03
2019-04
2019-05
2019-06
2019-07
2019-08
2019-09
2019-10
2019-11
2019-12
*/

Then left to associate.

Using laga window function data offset, it can be calculated.

select date_time,
       cnt,
       cnt_lag,
       cnt_diff,
       case when (round((case when cnt = 0 then null
              else cnt_diff/decode(cnt_lag, 0, 1, cnt_lag) end ) * 100, 2) is
              || '%' as rate
from 
(
select a.date_time,
       nvl(b.cnt, 0) as cnt,
       lag(nvl(b.cnt, 0), 1) over ( order by a.date_time) as cnt_lag,
       nvl(b.cnt, 0) - lag(nvl(b.cnt, 0), 1) over ( order by a.date_time) as cnt_diff     
from
(
    select '2019-' || lpad(rownum, 2, '0') as date_time 
    from dual 
    connect by level <= 12
) a
left join temp_cwh_test b
on a.date_time = to_char(b.date_time,'yyyy-mm')
order by a.date_time
) d
order by date_time
/*
1   2019-01 25          
2   2019-02 20  25  -5  -20
3   2019-03 63  20  43  215
4   2019-04 96  63  33  52.38
5   2019-05 25  96  -71 -73.96
6   2019-06 0   25  -25 
7   2019-07 12  0   12  1200
8   2019-08 39  12  27  225
9   2019-09 250 39  211 541.03
10  2019-10 0   250 -250    
11  2019-11 1   0   1   100
12  2019-12 525 1   524 52400                 
*/

Reference links: the Oracle MoM calculation example

Guess you like

Origin www.cnblogs.com/hider/p/12466471.html