MySQL中带有ORDER BY子句的累积总和

时间:2018-11-04 17:25:48

标签: mysql sql cumulative-sum

我想在MySQL中有一个累积列。当我使用不带ORDER BY子句的SQL命令时,就可以了。但是使用ORDER BY子句,结果是错误的。

我的SQL语句是:

SET @LastSumFee := 1000;
SELECT HioId, ApplyDate, ApplyTime, Idx, InputFee, OutputFee, (@LastSumFee := @LastSumFee + InputFee - OutputFee) AS SumFee
FROM HsbInOutView
WHERE HnId = 9 OR LHnId = 9
LIMIT 5;

对于此sql,结果正常(此结果是由phpMyAdmin生成的):

HioId   ApplyDate   ApplyTime   Idx     InputFee    OutputFee   SumFee  
168     1381/10/10  00:00:00    11      1085945     0           1086945
169     1381/10/21  00:00:00    12      0           600000      486945
170     1381/10/02  00:00:00    10      0           700000      -213055
171     1381/10/01  00:00:00    9       0           600000      -813055
180     1381/05/26  00:00:00    3       782040      0           -31015

现在,如果我将ORDER BY添加到这样的SQL命令中:

SET @LastSumFee := 1000;
SELECT HioId, ApplyDate, ApplyTime, Idx, InputFee, OutputFee, (@LastSumFee := @LastSumFee + InputFee - OutputFee) AS SumFee
FROM HsbInOutView
WHERE HnId = 9 OR LHnId = 9
ORDER BY ApplyDate, ApplyTime, Idx
LIMIT 5;

我得到了错误的结果(此结果是由phpMyAdmin产生的):

HioId   ApplyDate   ApplyTime   Idx     InputFee    OutputFee   SumFee  
193     1380/08/08  00:00:00    1       50000       0           4444879
1334    1380/08/08  00:00:00    36      0           50000       -6897369
194     1381/04/30  00:00:00    2       889100      0           5333979
1169    1381/04/30  00:00:00    127     0           889100      15774756
180     1381/05/26  00:00:00    3       782040      0           -31015

我希望得到以下结果:

HioId   ApplyDate   ApplyTime   Idx     InputFee    OutputFee   SumFee  
193     1380/08/08  00:00:00    1       50000       0           51000
1334    1380/08/08  00:00:00    36      0           50000       1000
194     1381/04/30  00:00:00    2       889100      0           890100
1169    1381/04/30  00:00:00    127     0           889100      1000
180     1381/05/26  00:00:00    3       782040      0           783040

1 个答案:

答案 0 :(得分:0)

在许多较新的MySQL版本中,您需要将该表具体化为派生表,以使其正常工作:

SELECT HioId, ApplyDate, ApplyTime, Idx, InputFee, OutputFee, 
       (@LastSumFee := @LastSumFee + InputFee - OutputFee) AS SumFee
FROM (SELECT v.*
      FROM HsbInOutView v
      WHERE HnId = 9 OR LHnId = 9
      ORDER BY ApplyDate, ApplyTime, Idx
     ) v CROSS JOIN
     (SELECT @LastSumFee := 1000) params
LIMIT 5;

当然

( 1000 + SUM(InputFee - OutputFee) OVER (ORDER BY ApplyDate, ApplyTime, Idx) ) as SumFee

要简单得多。