原理是一样的。。直接用开窗函数去依次减就行了
select tmp.* from (
select
a.月份,
a.金额,
b.退款总金额,
case when (b.退款总金额-sum(a.金额) over (order by a.月份 desc))<0 then 0 else
b.退款总金额-sum(a.金额) over (partition by a.月份 order by a.月份 desc) as 相减金额
/*月份要倒序排序*/
from testaa a
left join testbb b on a.id=b.id/*B表是你每个id对应的退款总金额表你改成你关联字段*/
) tmp
where 1=1
order by tmp.月份 asc/*这里要升序了。因为你展示的时候又和里面相减的顺序相反了*/
-------------以下是我在oracel模拟的---------hive是一样的原理----hive没有dual的这个虚拟表。我不好模拟了。。我没有在hive创建一个虚拟表
select tmp.* from (
select
t.month_code,
t.amount,
t.tot_amount,
case when t.tot_amount-sum(t.amount) over (order by t.month_code desc)<0 then 0 else
t.amount end as 金额判断
from (
select 1 as month_code,100 as amount,250 as tot_amount from dual union all
select 2 as month_code,100 as amount,250 as tot_amount from dual union all
select 3 as month_code,100 as amount,250 as tot_amount from dual union all
select 4 as month_code,100 as amount,250 as tot_amount from dual union all
select 5 as month_code,50 as amount,250 as tot_amount from dual)
t
) tmp
order by tmp.month_code