MySQL:根据2列累积值

时间:2017-08-24 12:24:44

标签: mysql

我有一张如下表格。我需要为每个用户累积值,但在月份中断时停止累积。

输入:

+----+-------------+----------------+
| id | month       | period         |
+----+-------------+----------------+
| A  | 2015-09-01  |              0 |
| A  | 2015-10-01  |              1 |
| A  | 2015-11-01  |             15 |
| A  | 2016-04-01  |              2 |
| A  | 2016-05-01  |              0 |
| B  | 2015-09-01  |              0 |
| B  | 2015-10-01  |              1 |
| B  | 2015-12-01  |             15 |
| B  | 2016-01-01  |              2 |
+----+-------------+----------------+

输出:

+----+-------------+----------------+-----------------------+
| id | month       | period         | result column         |
+----+-------------+----------------+-----------------------+
| A  | 2015-09-01  |              0 |                     0 |
| A  | 2015-10-01  |              1 |                     1 |
| A  | 2015-11-01  |             15 |                    16 |
| A  | 2016-04-01  |              2 |                     2 |
| A  | 2016-05-01  |              0 |                     2 |
| B  | 2015-09-01  |              0 |                     0 |
| B  | 2015-10-01  |              1 |                     1 |
| B  | 2015-12-01  |             15 |                    15 |
| B  | 2016-01-01  |              2 |                    17 |
+----+-------------+----------------+-----------------------+

1 个答案:

答案 0 :(得分:0)

E.g:

SELECT x.*
     , CASE WHEN @prev_id = id 
         THEN CASE WHEN @prev_month = month - INTERVAL 1 MONTH 
           THEN @i := @i+period ELSE @i := period END 
          ELSE @i := 0 END i
     , @prev_id := id
     , @prev_month := month 
  FROM my_table x
     , (SELECT @prev_id:=null,@prev_month:=null,@i:=0) vars 
 ORDER 
    BY id
     , month;

......或类似的东西