Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of all rows prior to (and including) date on current row in MYSQL

It's important to know that the date will be unknown during the query time, so I cannot just hard code a 'WHERE' clause.

Here's my table:

+-----------+----------+-------------+
| Date_ID   | Customer | Order_Count |
+-----------+----------+-------------+
| 20150101  | Jones    | 6           |
| 20150102  | Jones    | 4           |
| 20150103  | Jones    | 3           |
+-----------+----------+-------------+

Here's the desired output:

+-----------+----------+------------------+
| Date_ID   | Customer | SUM(Order_Count) |
+-----------+----------+------------------+
| 20150101  | Jones    | 6                |
| 20150102  | Jones    | 10               |
| 20150103  | Jones    | 13               |
+-----------+----------+------------------+

My guess is I need to use a variable or perhaps a join.

Edit: still not able to get it fast enough. very slow.

like image 845
Danny W Avatar asked Jul 30 '15 21:07

Danny W


People also ask

How do I get the sum of values in a row in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

Can we use sum function in WHERE clause?

In SQL, we use the SUM() function to add the numeric values in a column. It is an aggregate function in SQL. The aggregate function is used in conjunction with the WHERE clause to extract more information from the data.

What is the difference between count and sum in MySQL?

COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column. AVG() is used to calculate the average value of the specified numeric column.


1 Answers

Try this query; it's most likely the best you can do without limiting the dataset you operate on. It should benefit from an index (customer, date_id).

select 
  t1.date_id, t1.customer, sum(t2.order_count)
from 
  table1 t1
left join 
  table1 t2 on t1.customer = t2.customer
           and t1.date_id >= t2.date_id
group by 
  t1.date_id, t1.customer;

Sample SQL Fiddle.

like image 58
jpw Avatar answered Oct 06 '22 00:10

jpw