表结构是这样的
单位 | 年份 | 月份 | 月发生额 |
---|---|---|---|
A单位 | 2021 | 1 | 100 |
A单位 | 2021 | 2 | 200 |
A单位 | 2021 | 3 | 150 |
A单位 | 2021 | 4 | 330 |
A单位 | 2020 | 1 | 110 |
A单位 | 2020 | 2 | 120 |
B单位 | 2021 | 1 | 200 |
B单位 | 2021 | 2 | 350 |
B单位 | 2021 | 3 | 100 |
表结构中记录了每个月的月销售额,但现在想要得到每月累计销售额,也就是下表
单位 | 年份 | 月份 | 月累计发生额 |
---|---|---|---|
A单位 | 2021 | 1 | 100 |
A单位 | 2021 | 2 | 300 |
A单位 | 2021 | 3 | 450 |
A单位 | 2021 | 4 | 780 |
A单位 | 2020 | 1 | 110 |
A单位 | 2020 | 2 | 230 |
B单位 | 2021 | 1 | 200 |
B单位 | 2021 | 2 | 550 |
B单位 | 2021 | 3 | 650 |
想了很久,不晓得这种查询该怎么写,请教一下。
按照单位、年份对月发生额进行累计求和,可以参考下面语句
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 可以方便的计算出来
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