简体   繁体   中英

Calculate cumulative monthly and year value starting from given MTD and YTD

I have following data:

Name  | Production_day | tonnes |  MTD  | YTD
------------------------------------------
 gas  | 06/Aug/17      | 2047   | 15000 | 48000 
 gas  | 07/Aug/17      | 1547   |       | 
 gas  | 08/Aug/17      | 1747   |       | 
 gas2 | 06/Aug/17      | 3047   | 15050 | 48800 
 gas2 | 07/Aug/17      | 5547   |       | 
 gas2 | 08/Aug/17      | 9747   |       | 

I have given MTD and YTD and I need to calculate cumulative monthly and year tonnes value starting from given MTD and YTD.

Desired result so as example for gas, MTD=15000+1547, YTD=48000+1547 and etc:

Name  | Production_day | tonnes |  MTD  | YTD
------------------------------------------
 gas  | 06/Aug/17      | 2047   | 15000 | 48000 
 gas  | 07/Aug/17      | 1547   | 16547 | 49547
 gas  | 08/Aug/17      | 1747   | 18294 | 51294
 gas2 | 06/Aug/17      | 3047   | 15050 | 48800 
 gas2 | 07/Aug/17      | 5547   |       | 
 gas2 | 08/Aug/17      | 9747   |       | 

I could easily do it with query below but how to tell to start calculating from given MTD and YTD?:

select name,PRODUCTION_DAY, tonnes, sum(tonnes) over (partition by name,  to_char(PRODUCTION_DAY, 'MON-YYYY') order by PRODUCTION_DAY ) MTD from  MV_D_MAS_LASTYEAR order by name, PRODUCTION_DAY 

thanks, S

Define the groups by using a cumulative sum. Then use those groups for the cumulative sum:

select m.*,
       (sum(tonnes) over (partition by name, ytd_grp order by production_day) +
        max(ytd) over (partition by name, ytd_grp)
       ) as running_ytd,
       (sum(tonnes) over (partition by name, mtd_grp order by production_day) +
        max(mtd) over (partition by name, mtd_grp)
       ) as running_mtd
from (select m.*,
             sum(case when ytd is not null then 1 else 0 end) over (partition by name order by production_day) as ytd_grp,
             sum(case when mtd is not null then 1 else 0 end) over (partition by name order by production_day) as mtd_grp,
      from MV_D_MAS_LASTYEAR m
     ) m
order by name, PRODUCTION_DAY 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM