MYSQL查询金融订单簿的分组依据和累计金额

MYSQL query group by and cumulative sum for financial orderbook

你好,我有以下数据集

id price amount
1    10    1
2    20    2
3    20    1.5
4    21    1
5    21    2
SELECT amount, price, (@CumulativeSum := @CumulativeSum + amount) AS CumSum 
FROM orderbook 

它工作正常。我还想使用“GROUP BY price”子句填充我的 python 字典,但这会影响我的最终结果。最终数据应显示按价格分组的金额总和。

我尝试了以下查询

SELECT amount, price, (@CumulativeSum := @CumulativeSum + amount) AS CumSum 
FROM orderbook  
GROUP BY price

SELECT SUM(amount), price, (@CumulativeSum := @CumulativeSum + amount) AS CumSum 
FROM orderbook  
GROUP BY price

SELECT amount, price, (@CumulativeSum := @CumulativeSum + SUM(amount)) AS CumSum 
FROM orderbook 

但是累计和或者分组和总是错误的

最终结果应该是一个简单的金融市场订单簿。

期望的输出是

price amount CumSum
10    1     1
20    3.5   4.5
21    3     7.5

感谢提示

我用的是mysql 5.7(因为这个版本是我用的)。你想从每个价格的金额结果中累计求和,所以你应该使用 SUBQUERY 来聚合

试试这个:

    set @CumulativeSum := 0;
    SELECT price, summ,
   (@CumulativeSum:= @CumulativeSum + summ) as cumsum 
      FROM (SELECT SUM(amount) as Summ
             FROM (SELECT * FROM orderbook) a
             GROUP BY price
             ORDER BY price) b

结果

+-------+------+--------+
| price | summ | cumsum |
+-------+------+--------+
|    10 | 1.00 | 1.00   |
|    20 | 3.50 | 4.50   |
|    21 | 3.00 | 7.50   |
+-------+------+--------+

这是fiddlehttps://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=4f607e38a23f069829dfaa177a8bc3d3