Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate a running total in MySQL

Tags:

sql

mysql

I have this MySQL query:

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

Which returns something like this:

d  | COUNT(*) | 20 |  5       | 21 |  7       | 22 | 12       | 23 |  4       | 

What I'd really like is another column on the end to show the running total:

d  | COUNT(*) | ??? | 20 |  5       |   5 | 21 |  7       |  12 | 22 | 12       |  24 | 23 |  4       |  28 | 

Is this possible?

like image 715
nickf Avatar asked Mar 20 '09 01:03

nickf


People also ask

How do you calculate running total in SQL?

In this SQL Server example, we'll use the SUM Function and OVER to find the Running Total. Select in SQL Server Management Studio: Example 3: In this SQL Server example, we will use PARTITION BY with OVER to find the Running Total.

How does MySQL calculate total sum?

MySQL sum() function. The MySQL sum() function is used to return the total summed value of an expression. It returns NULL if the result set does not have any rows. It is one of the kinds of aggregate functions in MySQL.

How do you calculate cumulative total in SQL?

A Cumulative total or running total refers to the sum of values in all cells of a column that precedes the next cell in that particular column. As you can see the below screenshot which displays a cumulative total in column RUNNING TOTAL for column Value .

How do you calculate running percentage in SQL?

The subquery SELECT SUM(Sales) FROM Total_Sales calculates the sum. We can then divide the running total, "SUM(a2. Sales)", by this sum to obtain the cumulative percent to total for each row.


1 Answers

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.

like image 65
Autosoft Avatar answered Sep 24 '22 02:09

Autosoft