Calculate a running total in MySQL

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

    It is possible to calculate a running balance using a temporary table in MySQL. The following query should work:

    CREATE TEMPORARY table orders_temp1 (SELECT id, DAYOFYEAR(`date`)  AS d, COUNT(*) as total FROM  `orders` WHERE  `hasPaid` > 0 GROUP BY d ORDER  BY d);
    CREATE TEMPORARY table orders_temp2 (SELECT * FROM orders_temp1);
    SELECT d, total, (SELECT SUM(t2.total) FROM orders_temp2 t2 WHERE t2.id<=t1.id) as running_total FROM orders_temp1 t1;
    

    A temporary table is used for organizing the query. Note that a temporary table only exists for the duration of the connection to the MySQL server

    The above query uses a sub query, which returns balance of all rows in the temporary table upto and including the current row. The balance is assigned to the current row in the actual table

提交回复
热议问题