Calculate a running total in MySQL

后端 未结 8 2507
别那么骄傲
别那么骄傲 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:58

    SELECT 
       DAYOFYEAR(O.`date`)  AS d, 
       COUNT(*),
       (select count(*) from `orders` 
           where  DAYOFYEAR(`date`) <= d and   `hasPaid` > 0)
    FROM  
      `orders` as O
    WHERE  
      O.`hasPaid` > 0
    GROUP  BY d
    ORDER  BY d
    

    This will require some syntactical tuning (I don't have MySQL to test it), but it shows you the idea. THe subquery just has to go back and add up everything fresh that you already included in the outer query, and it has to do that for every row.

    Take a look at this question for how to use joins to accomplish the same.

    To address concerns about performance degradation with growing data: Since there are max. 366 days in a year, and I assume that you are not running this query against multiple years, the subquery will get evaluated up to 366 times. With proper indices on the date and the hasPaid flag, you'll be ok.

提交回复
热议问题