我有一个包含以下数据的表:
ID In Out 1 100.00 0.00 2 10.00 0.00 3 0.00 70.00 4 5.00 0.00 5 0.00 60.00 6 20.00 0.00
现在,我需要一个查询,该查询给出以下结果:
ID In Out Balance 1 100.00 0.00 100.00 2 10.00 0.00 110.00 3 0.00 70.00 40.00 4 5.00 0.00 45.00 5 0.00 60.00 -15.00 6 20.00 0.00 5.00
是否可以通过一个查询而不使用触发器或存储过程来做到这一点?
简短的回答,是的
更长的答案是,您可以使用变量在向下迭代行时对其进行计数,即
SELECT `table`.`ID`, `table`.`In`, `table`.`Out`, @Balance := @Balance + `table`.`In` - `table`.`Out` AS `Balance` FROM `table`, (SELECT @Balance := 0) AS variableInit ORDER BY `table`.`ID` ASC
将, (SELECT @Balance := 0) AS variableInit确保在开始之前@Balance被初始化为0。然后,对于每一行,将@Balance设置为@Balance + In - Out,然后输出计算出的值。
, (SELECT @Balance := 0) AS variableInit
@Balance + In - Out
同样值得确定的是ORDER是一致的,否则Balance会根据返回行的顺序而有所不同。例如,如果您想将其重新排序,则可以将其用作子查询,因为外部查询将处理计算出的值,从而确保余额保持正确,即
SELECT `balanceCalculation`.`ID`, `balanceCalculation`.`In`, `balanceCalculation`.`Out`, `balanceCalculation`.`Balance` FROM ( SELECT `table`.`ID`, `table`.`In`, `table`.`Out`, @Balance := @Balance + `table`.`In` - `table`.`Out` AS `Balance` FROM `table`, (SELECT @Balance := 0) AS variableInit ORDER BY `table`.`ID` ASC ) AS `balanceCalculation` ORDER BY `balanceCalculation`.`ID` DESC