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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With