有没有办法从前一行中减去数据到当前行并将其保存到当前行

时间:2017-04-08 04:48:29

标签: mysql

我有三列:

monthly   fee   remaining

第一行 - 条件:

subtract fee(row 0) from monthly(row 0) and stored in remaining(row 0)

第二行及以后 - 条件:

subtract fee(this row) from remaining(previous row) and stored in remaining(this row)

我应该使用什么查询来执行此操作?我在这方面需要帮助。

2 个答案:

答案 0 :(得分:0)

在这两列上获取两个单独的子查询,并在两个子查询中包含所需信息,并以任何可能的方式为该字段(您想要执行此操作)提供行号。现在根据rownumber和rownumber + 1继续加入这两个子查询,现在你将获得两个列,选择rownumber字段和rownumber + 1字段。将其他选择中的差异视为其他字段。

希望你理解它。请完全注意并按照你做这件事的具体栏目下订单。

答案 1 :(得分:0)

如果您要在select语句中执行此操作,则代码实际上看起来像

select @recordnumber:=@recordnumber+1 as recordnumber,
@curremaining:=if(@curremaining=0,Monthly,@remaining) prevremaining,
Monthly, Fee, @remaining:=@curremaining-Fee as remaining 
from Payments,(select @remaining:=0,@curremaining:=0,@recordnumber:=0) x;

在查询记录时,您可能需要订购,只需在sql语句的末尾添加订单。即

from Payments,(select @remaining:=0,@curremaining:=0,@recordnumber:=0) x
order by fieldtoorder;