2017-08-24 90 views
-2

我有一張如下表格。我需要爲每個用戶累計值,但在當月有休息時停止累計。MySQL:基於2列的累積值

輸入:

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

輸入: + ---- + ------------- + ---- ------------ + | id |月|週期| + ---- + ------------- + ---------------- + | 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 | + ---- + ------------- + ---------------- + –

+0

在你的問題中沒有問題。 – gdir

+0

我想寫一個查詢來獲取我發佈的輸出 –

回答

0

如:

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; 

...或者類似的東西