如何在SQL中逐行创建部分余额

时间:2014-01-22 15:18:54

标签: mysql sql

我正在尝试使用部分余额进行查询,其中最后一列是一行一行:

此处有一组数据 A 日期为DD-MM-YYYY

Amount | Date       
20     | 16-01-2013
 -1     | 22-01-2013
 -2     | 22-01-2013
 -3     | 23-01-2013
-9    | 24-01-2013

这里有一组数据 B

Amount | Date       
-5     | 23-01-2013
 -4     | 23-01-2013
 9     | 23-01-2013
 3     | 24-01-2013
-3    | 24-01-2013

我想得到这样的结果,让我们说一下数据集A:

Amount | Date | Balance

-9 | 24-01-2013 | 14
-3  | 23-01-2013 | 17
-2  | 22-01-2013 | 19
-1 | 22-01-2013 | 20
20  | 16-01-2013 | 0

我正在对这两个数据集使用此查询:

  SELECT
    PreAgg.tData,
    PreAgg.amount,
    @PrevBal := @PrevBal - PreAgg.amount AS Total
FROM
    (
        SELECT
            pr.tData,
            pr.amount

        FROM
            tableTest pr
        ORDER BY
            pr.tData desc
    ) AS PreAgg,
    (SELECT @PrevBal := 0.00) AS SqlVars

对于数据集B来说,它对于数据集A是完美的,但它没有,我无法理解为什么!

非常感谢

嗨,最后我设法做到了。

我在这里使用假计数器查询:

 SELECT
 reference,amount,balance
 FROM
 (
 SELECT
 @id := @id + 1 AS id,t.date as reference,t.amount,
 @balance := (@balance + t.amount) AS balance
 FROM
 tmpTable t, (SELECT @id:=0, @balance:=0, @grouping:=0) AS vars
 ORDER BY
 t.tData
 ) AS x
 ORDER BY
 x.id DESC

1 个答案:

答案 0 :(得分:0)

如果我将日期解释为DD-MM-YYYY,您的结果才有意义。否则,日期会出现乱码。

假设日期存储为日期(而不是字符串),您需要“asc”而不是“desc”:

SELECT (@rownumIn :=amount+@rownumIn) AS Balance, date, amount
FROM table_data cross join
     (SELECT @rownumIn := 0
     ) AS counter
WHERE some constraits
ORDER BY date asc;

我怀疑你犯了将日期存储为字符串的罪行。如果是这种情况,可以使用str_to_date()

轻松修复
SELECT (@rownumIn :=amount+@rownumIn) AS Balance, date, amount
FROM table_data cross join
     (SELECT @rownumIn := 0
     ) AS counter
WHERE some constraits
ORDER BY str_to_date(date, '%d-%m-%Y') asc;