7

我有一个包含以下数据的表:

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

是否可以通过一个查询来执行此操作,而不使用触发器或存储过程?

4

3 回答 3

17

简短的回答,是的

更长的答案,您可以使用一个变量来计算它,因为它迭代行,即

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,然后输出计算值。

此外,值得确定 ORDER 是一致的,否则余额将根据返回的行的顺序而有所不同。例如,如果您想将其重新排序,例如,您可以将其用作子查询,因为外部查询处理计算值,从而确保余额保持正确,即

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
于 2012-02-22T12:11:13.170 回答
4

最简单的答案是:

SELECT `ID`, 
       `In`, 
       `Out`, 
       @running_bal := @running_bal + (`In` - `Out`)  as `Balance`
FROM   tableName, (SELECT @running_bal := 0) tempName
于 2012-02-22T12:16:30.350 回答
0

一个简单的LEFT JOIN就足够了:

SELECT t.ID, t.In, t.Out, (SUM(t2.In) - SUM(t2.Out)) Balance
FROM mytable t
    LEFT JOIN mytable t2 ON b2.ID <= b.ID
GROUP BY b.ID

或子查询(事实证明它的速度大约是原来的两倍)

SELECT t.ID, t.In, t.Out,
    (SELECT SUM(t2.In) - SUM(t2.Out) FROM mytable t2 WHERE t2.ID <= t.ID) Balance
FROM mytable t;
于 2017-01-27T04:58:51.190 回答