【问题标题】:How to make accumulative count based on date in MySQL?如何在 MySQL 中根据日期进行累积计数?
【发布时间】:2016-05-06 09:16:13
【问题描述】:

我有下表“testfinal”,并希望使其看起来像表“testfinal1”,并根据订单日期累积总和。

最终测试

+------+------------+-------+--------+----------+
| 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 |
+------+------------+-------+--------+----------+

现在我的代码如下但它不起作用

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;

我认为问题是没有指定术语 orderdate。

【问题讨论】:

  • 为什么需要条件?只做SELECT ID, Orderdate, SUM(apple), SUM(banana), SUM(quantity) FROM testfinal GROUP BY ID, Orderdate有什么问题?
  • testfina1 表中的最后一行是否正确? 1006 | 2011-10-06 | 1 | 3 | 4 。不应该是1006 | 2011-10-06 | 1 | 0 | 4 这个吗?
  • 您能解释一下您的预期输出吗?
  • 感谢您的评论。最后一行是1的原因| 3 | 4 是因为它是testfinal 表中(0 + 1)、(3+0)、(3+1) 的结果。
  • 在原始testfinal table上它是orderdate订购的货物数量。我想让新表“testfinal1”根据“orderdate”总结ID购买的商品,也就是说,ID在20110506买过(0,3),分别买过(1,0)在 20111006。在 testfinal2 表中,我想显示用户 ID 1006 从过去到 20111006 总共购买了 (1,3)。

标签: mysql date accumulate


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多