退款金额怎么从下往上减钱?

如图,我有三个字段,我想把退款字段变成E列这样,SQL该怎么写?

3cab04833c86d8b1315415ad2b9672f.jpg

三·金 发布于 2022-7-18 17:22
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共4回答
最佳回答
0
free_zzLv6中级互助
发布于2022-7-19 09:39(编辑于 2022-7-19 09:42)

我这是mysql,想退多少退多少~~image.png623f0e2e311aed2c70654e28d1ca889.pngf1a2ec55016d85961abf8fbe4214d9a.png

最佳回答
1
CD20160914Lv8专家互助
发布于2022-7-18 17:56(编辑于 2022-7-18 18:09)

原理是一样的。。直接用开窗函数去依次减就行了

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

image.png

最佳回答
0
Z4u3z1Lv6专家互助
发布于2022-7-18 17:23

啥数据库?

  • 三·金 三·金(提问者) hive的
    2022-07-18 17:26 
  • Z4u3z1 Z4u3z1 回复 三·金(提问者) 抱歉没用过写不了。如果没人提供SQL 可以考虑用层次坐标算
    2022-07-18 17:29 
  • 三·金 三·金(提问者) 回复 Z4u3z1 MYSQL应该也差不多吧,有啥思路么
    2022-07-18 17:33 
最佳回答
0
linbodingLv6中级互助
发布于2022-7-18 17:24(编辑于 2022-7-18 17:26)

你这很明显是c列是汇总数据,你要从明细数据中去找e列这样的数据。

没法从汇总去拆成明细,因为你根本不知道具体的数据是这么的,完全无规则

  • 三·金 三·金(提问者) c列存的是一个总金额,我现在需要拆分来退钱,退的逻辑是从下往上退
    2022-07-18 17:27 
  • linboding linboding 回复 三·金(提问者) 做不到,你可以去汇总,但你不可能由汇总变明细,没有规则
    2022-07-18 17:29 
  • 三·金 三·金(提问者) 回复 linboding 规则就是总共退250,从下往上退钱,到3月的时候,就退完了,所以1、2月是0
    2022-07-18 17:31 
  • linboding linboding 回复 三·金(提问者) 那你是固定每个月退100,直到退完吗?
    2022-07-18 17:32 
  • 三·金 三·金(提问者) 回复 linboding 根据前面缴费的金额来退钱
    2022-07-18 17:33 
  • 4关注人数
  • 384浏览人数
  • 最后回答于:2022-7-19 09:42
    请选择关闭问题的原因
    确定 取消
    返回顶部