Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

MYSQL query group by and cumulative sum for financial orderbook

Hello i have the following dataset

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 

And it is working fine. I would like to populate my python dictionary using also a "GROUP BY price" clause but this is affecting my final result. The final data should show the SUM of the amounts grouped by price.

I tried the following queries

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 

But the cumulative sum or the grouped sums are always wrong.

The final result should be a simple order book for a financial market.

The desired output is

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

Thanks for the hints

question from:https://stackoverflow.com/questions/65925372/mysql-query-group-by-and-cumulative-sum-for-financial-orderbook

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I use mysql 5.7 (since this version is using by me). you want to sum cummulative from the result of amount on each price, so you should use SUBQUERY in order to aggregation

Try this:

    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

result

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

this is the fiddle https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=4f607e38a23f069829dfaa177a8bc3d3


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...