按项目和周计算总计

时间:2018-03-07 16:32:12

标签: mysql sql running-total

我正在尝试确定每个产品在每个工作周结束时的库存水平。

我有一张记录所有产品交易的表

+------------+-------------+------------+------------+
| ProductID  | Quantity    | Created_at |Cause       |
+------------+-------------+------------+------------+
|          1 | 200         | 2015-06-01 |Delivery    |
|          1 | -2          | 2015-06-02 |Order       |
|          1 | -1          | 2015-06-12 |Order       |
|          2 | 45          | 2015-06-15 |Delivery    |
|          2 | -5          | 2015-06-16 |Order       |
|          2 | -1          | 2015-06-17 |Broken      |
|          1 | 100         | 2015-06-21 |Delivery    |
+------------+-------------+------------+------------+

我需要将产品的数量总和到产品的特定日期,以显示类似的内容

+------------+-------------+------------+
| ProductID  | Quantity    | Week       |
+------------+-------------+------------+
|          1 | 198         | 2015-06-05 |
|          1 | 197         | 2015-06-12 |
|          1 | 197         | 2015-06-19 |
|          2 | 39          | 2015-06-19 |
|          1 | 297         | 2015-06-26 |
|          2 | 39          | 2015-06-26 |
+------------+-------------+------------+

我尝试过使用Rollup和@runtot:=的各种组合 但到目前为止还没有成功。

1 个答案:

答案 0 :(得分:2)

所以,比如:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(product_id INT NOT NULL
,created_at DATE NOT NULL 
,quantity INT NOT NULL
,cause  VARCHAR(20) NOT NULL
,PRIMARY KEY(product_id,created_at)
);

INSERT INTO my_table VALUES
(1,'2015-06-01',200,'Delivery'),
(1,'2015-06-02', -2,'Order'),
(1,'2015-06-12', -1,'Order'),
(2,'2015-06-15', 45,'Delivery'),
(2,'2015-06-16', -5,'Order'),
(2,'2015-06-17', -1,'Broken'),
(1,'2015-06-21',100,'Delivery');

SELECT x.*
     , CASE WHEN @prev = product_id THEN @i:=@i+total ELSE @i:=total END running
     , @prev:=product_id prev 
  FROM 
     ( SELECT product_id
            , YEARWEEK(created_at) yw
            , SUM(quantity) total 
         FROM my_table
        GROUP 
           BY product_id
            , yw
     ) x
     , (SELECT @prev:=null,@i:=0) vars 
 ORDER 
    BY product_id
     , yw;
+------------+--------+-------+---------+------+
| product_id | yw     | total | running | prev |
+------------+--------+-------+---------+------+
|          1 | 201522 |   198 |     198 |    1 |
|          1 | 201523 |    -1 |     197 |    1 |
|          1 | 201525 |   100 |     297 |    1 |
|          2 | 201524 |    39 |      39 |    2 |
+------------+--------+-------+---------+------+