mysql - MYSQL 中当前行上(和包括)日期之前的所有行的总和

标签 mysql sql cumulative-sum

重要的是要知道在查询期间日期是未知的,所以我不能只硬编码“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;

Sample SQL Fiddle .

关于mysql - MYSQL 中当前行上(和包括)日期之前的所有行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734599/

相关文章:

mysql - 计算MySQL中组记录的总和

php - 使用 Laravel 的 Eloquent 或查询构建器加快数据库访问速度

c# - C# 中带有字典的 InvalidCastException

sql - 在 Rails AR 中增加字段值的安全方法

mysql - 如何查找其中包含某些行值的列/表

python - 确定一对骰子获得 1-1 结果的平均掷骰次数

python - 根据另一列重置累计总和

php - 错误 1045 : access denied for user 'root' @'localhost' using password NO. .. 通过扩展类连接时,其他

postgresql - postgres - 根据条件计算累计和

具有多种连接可能性的连接更新 MySQL