Calculate a running total in MySQL

后端 未结 8 2328
别那么骄傲
别那么骄傲 2020-11-22 00:37

I have this MySQL query:

SELECT DAYOFYEAR(`date`)  AS d, COUNT(*) 
FROM  `orders` 
WHERE  `hasPaid` > 0
GROUP  BY d
ORDER  BY d

Which re

8条回答
  •  無奈伤痛
    2020-11-22 00:43

    Perhaps a simpler solution for you and prevents the database having to do a ton of queries. This executes just one query then does a little math on the results in a single pass.

    SET @runtot:=0;
    SELECT
       q1.d,
       q1.c,
       (@runtot := @runtot + q1.c) AS rt
    FROM
       (SELECT
           DAYOFYEAR(`date`) AS d,
           COUNT(*) AS c
        FROM  `orders`
        WHERE  `hasPaid` > 0
        GROUP  BY d
        ORDER  BY d) AS q1
    

    This will give you an additional RT (running total) column. Don't miss the SET statement at the top to initialize the running total variable first or you will just get a column of NULL values.

提交回复
热议问题