我有以下数据:
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 | |
我已经给出了MTD和YTD,我需要从给定的MTD和YTD开始计算累计月和年吨值。
期望的结果,例如气体,MTD = 15000 + 1547,YTD = 48000 + 1547等:
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 | |
我可以通过下面的查询轻松完成,但如何判断从给定的MTD和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
感谢, 小号
答案 0 :(得分:0)
使用累积总和定义组。然后将这些组用于累积总和:
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