重要的是要知道在查询期间日期是未知的,所以我不能只硬编码“WHERE”子句。
这是我的 table :
+-----------+----------+-------------+
| Date_ID | Customer | Order_Count |
+-----------+----------+-------------+
| 20150101 | Jones | 6 |
| 20150102 | Jones | 4 |
| 20150103 | Jones | 3 |
+-----------+----------+-------------+
这是期望的输出:
+-----------+----------+------------------+
| Date_ID | Customer | SUM(Order_Count) |
+-----------+----------+------------------+
| 20150101 | Jones | 6 |
| 20150102 | Jones | 10 |
| 20150103 | Jones | 13 |
+-----------+----------+------------------+
我的猜测是我需要使用变量或连接。
编辑:仍然不够快。很慢。
最佳答案
试试这个查询;在不限制您操作的数据集的情况下,这很可能是您可以做的最好的事情。它应该受益于索引(客户,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;
关于mysql - MYSQL 中当前行上(和包括)日期之前的所有行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734599/