2017-04-23 33 views
1

表score_streak用於存儲用戶的每日分數並且定義如下。從用戶分數表中獲取連續日期的所有條紋

CREATE TABLE IF NOT EXISTS score_streak(
    create_date DATE NOT NULL, 
    score INT(11), 
    PRIMARY KEY (create_date) 
); 

insert into score_streak (create_date, score) values 
    (DATE('2017-04-01'), 11) , 
    (DATE('2017-04-02'), 8) , 
    (DATE('2017-04-03'), 9) , 
    (DATE('2017-04-06'), 14) , 
    (DATE('2017-04-07'), 15) , 
    (DATE('2017-04-08'), 13) , 
    (DATE('2017-04-12'), 20) , 
    (DATE('2017-04-13'), 21) , 
    (DATE('2017-04-14'), 22) , 
    (DATE('2017-04-15'), 18) ; 

select * from score_streak; 
    create_date | score 
    2017-04-01 | 11 
    2017-04-02 | 8 
    2017-04-03 | 9 
    2017-04-06 | 14 
    2017-04-07 | 15 
    2017-04-08 | 13 
    2017-04-12 | 20 
    2017-04-13 | 21 
    2017-04-14 | 22 
    2017-04-15 | 18 

我想查詢該表來獲取所有條紋在用戶的得分大於或等於10且日期必須是連續的。每個連勝都有一個開始日期和一個結束日期。

例如,上面在下文提供的採樣數據的預期結果(注意,有3個條紋):

start_date | end_date |streak_count 
2017-04-01 | 2017-04-01 |  1 
2017-04-06 | 2017-04-08 |  3 
2017-04-12 | 2017-04-15 |  4 

感謝。

+0

該日期東西是不必要的 – Strawberry

回答

1

你可以做

SELECT MIN(create_date) start_date, 
     MAX(create_date) end_date, 
     COUNT(*) streak_count 
    FROM (
    SELECT q.*, 
      @g := @g + COALESCE(DATEDIFF(create_date, @p) <> 1, 0) gn, 
      @p := create_date 
     FROM (
     SELECT * 
      FROM score_streak 
     WHERE score > 9 
     ORDER BY create_date 
    ) q CROSS JOIN (
     SELECT @g := 0, @p := NULL 
    ) i 
) r 
GROUP BY gn 

輸出:

 
+------------+------------+--------------+ 
| start_date | end_date | streak_count | 
+------------+------------+--------------+ 
| 2017-04-01 | 2017-04-01 |   1 | 
| 2017-04-06 | 2017-04-08 |   3 | 
| 2017-04-12 | 2017-04-15 |   4 | 
+------------+------------+--------------+ 

SQLFiddle

相關問題