Calculate balance with mysql

后端 未结 3 746
野的像风
野的像风 2020-12-14 13:20

I have a table which contains the following data:

ID      In       Out 
1      100.00    0.00   
2       10.00    0.00   
3        0.00   70.00    
4                 


        
3条回答
  •  我在风中等你
    2020-12-14 13:57

    Short answer, yes

    Longer answer, you can use a variable to tally it up as it iterates down the rows, i.e.

    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
    

    The , (SELECT @Balance := 0) AS variableInit ensures that @Balance is initialised to 0 before you start. For each row it then sets @Balance to be @Balance + In - Out, and then outputs the calculated value.

    Also it's worth making certain the ORDER is consistent as otherwise the Balance will vary depending on what order the rows are returned. If you wanted to then order it back to front, for example, you could use this as a subquery as then the outer query deals with the calculated values thus ensuring the Balance remains correct i.e.

    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
    

提交回复
热议问题