0

I have the following table "testfinal"and would like to make it look like table "testfinal1" with accumulative sum based on orderdate.

testfinal

+------+------------+-------+--------+----------+
| ID   | Orderdate  | apple | banana | quantity |
+------+------------+-------+--------+----------+
| 1005 | 2015-05-05 |     2 |      0 |        2 |
| 1005 | 2015-05-05 |     0 |      2 |        2 |
| 1005 | 2015-05-06 |     0 |      1 |        1 |
| 1006 | 2011-05-06 |     0 |      3 |        3 |
| 1006 | 2011-10-06 |     1 |      0 |        1 |
+------+------------+-------+--------+----------+

testfinal1

+------+------------+-------+--------+----------+
| ID   | Orderdate  | apple | banana | quantity |
+------+------------+-------+--------+----------+
| 1005 | 2015-05-05 |     2 |      2 |        4 |
| 1005 | 2015-05-06 |     2 |      3 |        5 |
| 1006 | 2011-05-06 |     0 |      3 |        3 |
| 1006 | 2011-10-06 |     1 |      3 |        4 |
+------+------------+-------+--------+----------+

Now my code is as follows but it doesn't work

insert into testfinal1 (ID, Orderdate, apple, banana, quantity) 
select ID, Orderdate, 
(select sum(apple)from testfinal where date_format(OrderDate, '%Y-%m-%d') <= date_format(OrderDate, '%Y-%m-%d' ))  as apple, 
(select sum(banana)from testfinal where date_format(OrderDate, '%Y-%m-%d') <= date_format(OrderDate, '%Y-%m-%d' ))  as banana, 
(select sum(quantity)from testfinal where date_format(OrderDate, '%Y-%m-%d') <= date_format(OrderDate, '%Y-%m-%d' ))  as quantity 
from testfinal group by ID, Orderdate;

I think the problem is the term orderdate is not specified.

4

1 回答 1

1

这是您可能需要首先生成的查询:

SELECT
ID,
Orderdate,
SUM(apple) AS 'apple',
SUM(banana) AS 'banana',
SUM(quantity) AS 'quantity'
FROM testfinal
GROUP BY Orderdate;

DROP TABLE IF EXISTS testfinal1;

CREATE TABLE testfinal1 LIKE testfinal;

INSERT INTO testfinal1(ID,Orderdate,apple,banana,quantity)

SELECT
ID,
Orderdate,
SUM(apple) AS 'apple',
SUM(banana) AS 'banana',
SUM(quantity) AS 'quantity'
FROM testfinal
GROUP BY Orderdate;
于 2016-05-06T09:23:03.130 回答