Calculate a running total in MySQL

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

    Starting with MySQL 8, you will be using window functions for this kind of query:

    SELECT dayofyear(`date`) AS d, count(*), sum(count(*)) OVER (ORDER BY dayofyear(`date`))
    FROM `orders`
    WHERE `hasPaid` > 0
    GROUP BY d
    ORDER BY d
    

    In the above query, the aggregate function count(*) is nested inside of the window function sum(..) OVER (..), which is possible because of the logical order of operations in SQL. If that's too confusing, you can easily resort to using a derived table or a WITH clause to better structure your query:

    WITH daily (d, c) AS (
      SELECT dayofyear(`date`) AS d, count(*)
      FROM `orders`
      WHERE `hasPaid` > 0
      GROUP BY d
    )
    SELECT d, c, sum(c) OVER (ORDER BY d)
    ORDER BY d
    

提交回复
热议问题