MySQL如何创建一个运行总计

时间:2018-03-16 16:40:44

标签: mysql

我在table_1中有一些数据:

order_id | cust_id | order_date | city_id
101        |    1    | 15/03/2018 |     1001
102        |    1    | 15/03/2018 |     1005
103        |    2    | 10/03/2018 |     1001
104        |    4    | 16/02/2018 |     1006
105        |    4    | 10/01/2018 |     1250
106        |    4    | 15/03/2018 |     1250
107        |    6    | 16/02/2018 |     1058
108        |    6    | 10/03/2018 |     1058
109        |    4    | 23/02/2018 |     1006
110        |    7    | 19/01/2018 |     1005
111        |    7    | 21/01/2018 |     1005
...

我在table_2中有这些数据

city_id | city_name
  1001  |   New York
  1005  |  London
  1006  |  Brighton
  1250  |  Toronto
  1058  | Manchester

我需要查找过去10周伦敦的每周订单数量,以及累计总数。

这只是我正在使用的数据的一个子集。

到目前为止,我已经尝试过这个:

set @running_total:=0;
select week(a.order_date) as week_start,
    count(a.order_id) as order_count,
    (
        @running_total := @running_total + count(a.order_id)
        ) as cuml_count
from table_1 a
    left join table_2 b on a.city_id = b.city_id
    join (SELECT @running_total := 0) r
where b.city_name = "London"
group by 1
;

但是生成的cuml_count与order_count匹配。在我正在使用的数据上看起来像:

week_start | order_count | cuml_count
     2     |      1      |      1
     3     |      1      |      1
     10    |      1      |      1

应该看起来像:

week_start | order_count | cuml_count
         2     |      1      |      1
         3     |      1      |      2
         10    |      1      |      3

1 个答案:

答案 0 :(得分:2)

您可以查看此SO帖子了解详情 Calculate a running total in MySQL

但是像:

SET @running_total:=0;
SELECT 
    week_start, 
    order_count,
    (@running_total := @running_total + order_count) AS cuml_count
FROM (
    SELECT week(t1.order_date) as week_start,
    COUNT(t1.order_date) AS order_count
    FROM table_1 AS t1
        LEFT JOIN
            table_2 AS t2 
            ON t1.city_id = t2.city_id
    WHERE t2.city_name = "London"
    GROUP BY week_start
) AS temp
ORDER BY week_start

可能适合你

修改:http://sqlfiddle.com/#!9/f8f806/5 为OP&创建了一个添加了ORDER BY

编辑:移动到@ Strawberry的ORDER BY位置,选择中的init也非常好!