Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following set of data in a MySQL database table

 CusName   CusID    Quantity   Date
 Test1      1        2         2017-01-01
 Test1      1        1.5       2017-01-10
 Test1      1        5         2017-01-25
 Test2      2        0.5       2017-01-02
 Test2      2        3         2017-01-05
 Test3      3        10        2017-01-01
 Test4      4        4         2017-01-18
 Test4      4        6         2017-01-19

I need to create a php script to calculate cumulative totals for the quantity for each customer as follows

 CusName   CusID    Quantity   QuantityTotal  Date
 Test1      1        2          2             2017-01-01
 Test1      1        1.5        3.5           2017-01-10
 Test1      1        5          8.5           2017-01-25
 Test2      2        0.5        0.5           2017-01-02
 Test2      2        3          3.5           2017-01-05
 Test3      3        10         10            2017-01-01
 Test4      4        4          4             2017-01-18
 Test4      4        6          10            2017-01-19
See Question&Answers more detail:os

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

1 Answer

One approach is to use a correlated subquery:

SELECT
    CusName,
    CusID,
    Quantity,
    (SELECT SUM(t2.Quantity) FROM yourTable t2
     WHERE t2.CusID = t1.CusID AND t2.Date <= t1.Date) QuantityTotal,
    Date
FROM yourTable t1
ORDER BY
    CusID,
    Date;

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...