Oracle根据月发生额算出每月累计发生额查询该如何写

表结构是这样的

单位年份月份月发生额
A单位20211100
A单位20212200
A单位20213150
A单位20214330
A单位20201110
A单位20202120
B单位20211200
B单位20212350
B单位20213100

表结构中记录了每个月的月销售额,但现在想要得到每月累计销售额,也就是下表

单位年份月份月累计发生额
A单位20211100
A单位20212300
A单位20213450
A单位20214780
A单位20201110
A单位20202230
B单位20211200
B单位20212550
B单位20213650

想了很久,不晓得这种查询该怎么写,请教一下。

按照单位、年份对月发生额进行累计求和,可以参考下面语句

SELECT 单位字段,年份字段,月份字段,sum(月发生额) over(partition by 单位字段,年份字段 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) LJ
FROM 表名

上面回答使用子查询的方法不可取。数据量稍微大一些的时候你根本算不出结果。
可以使用分析函数。通过sum over进行连续求和。下面是一个例子可直接运行

with sj as
 (select 'A单位' dw, 2021 year, 1 month, 100 je
    from dual
  union all
  select 'A单位' dw, 2021 year, 2 month, 200 je
    from dual
  union all
  select 'A单位' dw, 2021 year, 3 month, 150 je
    from dual
  union all
  select 'A单位' dw, 2021 year, 4 month, 330 je
    from dual
  union all
  select 'A单位' dw, 2020 year, 1 month, 110 je
    from dual
  union all
  select 'A单位' dw, 2020 year, 2 month, 120 je
    from dual
  union all
  select 'B单位' dw, 2021 year, 1 month, 200 je
    from dual
  union all
  select 'B单位' dw, 2021 year, 2 month, 350 je
    from dual
  union all
  select 'B单位' dw, 2021 year, 3 month, 100 je
    from dual)
  
select t.dw,
       t.year,
       t.month,
       sum(je) over(partition by dw, year order by dw asc, year desc, month asc) 累计发生额
  from sj t



很经典的一个开窗函数例子,楼上已有解答

使用 cte 可以方便的计算出来

也可以直接 cross 一下,


select * from tableA a
cross apply (
   select sum(月发生) as 月累计发生
   from tableA
   where 年份=a.年份 and 月份<=a.月份
) b

select 单位,年份,月份,(select sum(月发生额) from table b where a.单位=b.单位 and a.年份=b.年份 and b.月份<=a.月份) as 月累计发生额 from table a