mysql 减法,如何从MYSQL中的其他列运行减法

I have sample Data :

Month Val Bval

Jan 2020 12000 0

Feb 2020 0

Mar 2020 100

Apr 2020 0

May 2020 500

Jun 2020 1000

I want to subtract the column values with beside value column . Need to get output like this :

Month Val Bval

Jan 2020 12000 0

Feb 2020 12000 0

Mar 2020 11900 100

Apr 2020 11900 0

May 2020 11400 500

Jun 2020 10400 1000

I have tried with Co related query :

SELECT t.Month,

t.Bval,

(SELECT x.val -t.Bval

FROM TABLE x

WHERE x.Month <= t.Month) AS Val

FROM TABLE t

ORDER BY t.Month

Not getting proper result .

Can any one suggest me the suitable way

解决方案

With a self join and aggregation:

select t1.Month, sum(t2.Val) - sum(t2.Bval) Val, t1.Bval

from tablename t1 left join tablename t2

on str_to_date(concat(t1.Month, ' 01'), '%b %Y %d') >= str_to_date(concat(t2.Month, ' 01'), '%b %Y %d')

group by t1.Month, t1.Val, t1.Bval

order by str_to_date(concat(t1.Month, ' 01'), '%b %Y %d')

See the demo.

Results:

> Month | Val | Bval

> :------- | ----: | ---:

> Jan 2020 | 12000 | 0

> Feb 2020 | 12000 | 0

> Mar 2020 | 11900 | 100

> Apr 2020 | 11900 | 0

> May 2020 | 11400 | 500

> Jun 2020 | 10400 | 1000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值