【发布时间】:2016-05-06 18:19:27
【问题描述】:
我有一张如下表
+------+------------+-------+
| ID | orderdate | apple |
+------+------------+-------+
| 1005 | 2015-05-05 | 2 |
| 1005 | 2015-05-06 | 0 |
| 1006 | 2011-05-06 | 3 |
| 1006 | 2011-10-06 | 3 |
+------+------------+-------+
我想在 orderdate 上对苹果求和,以查看一个 ID 购买的苹果的累计总量。 例如,对于 ID 1006,此人在 2015-05-06 购买了 3 个苹果,并在 2011-10-06 购买了 3 个苹果,因此在 2015-05-06 日期,ID 1006 购买了 6 个,即由 (3+3) 计算,苹果总数。 因此,我的表格如下所示:
+------+------------+--------------------+
| ID | orderdate | accumulative apple |
+------+------------+--------------------+
| 1005 | 2015-05-05 | 2 |
| 1005 | 2015-05-06 | 2 | (0 + 2 )
| 1006 | 2011-05-06 | 3 |
| 1006 | 2011-10-06 | 6 | (3 + 3)
+------+------------+--------------------+
我的代码如下所示,但结果却是一个非常奇怪的结果.. 有人可以帮我解决这个问题吗?
select a.ID ID, a.orderdate orderdate, sum(b.apple) apple
from testfinal3 a
join testfinal3 b
on date_format(b. OrderDate, '%Y-%m-%d') >= date_format(a. OrderDate, '%Y-%m-%d')
group by ID, orderdate
order by ID, orderdate;
【问题讨论】: