从用户分数表中获取连续日期的所有条纹

时间:2017-04-23 05:29:14

标签: mysql sql

表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

感谢。

1 个答案:

答案 0 :(得分:1)

你可以做到

[ { type: 'FETCH_LYRIC' },
        { type: 'FETCH_LYRIC_ERROR',
          payload:
           SyntaxError
               at XMLHttpRequest.open (<user>/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:486:15)
               at XMLHttpRequest.tryCatcher (<user>/node_modules/rxjs/util/tryCatch.js:6:31)
               at AjaxSubscriber.Object.<anonymous>.AjaxSubscriber.send (<user>/node_modules/rxjs/observable/dom/AjaxObservable.js:208:56)
               at new AjaxSubscriber (<user>/node_modules/rxjs/observable/dom/AjaxObservable.js:180:14)
               at AjaxObservable.Object.<anonymous>.AjaxObservable._subscribe (<user>/node_modules/rxjs/observable/dom/AjaxObservable.js:115:16)
               at AjaxObservable.Object.<anonymous>.Observable._trySubscribe (<user>/node_modules/rxjs/Observable.js:57:25)
               at AjaxObservable.Object.<anonymous>.Observable.subscribe (<user>/node_modules/rxjs/Observable.js:45:27)
               at MapOperator.Object.<anonymous>.MapOperator.call (<user>/node_modules/rxjs/operator/map.js:54:23)
               at Observable.Object.<anonymous>.Observable.subscribe (<user>/node_modules/rxjs/Observable.js:42:22)
               at MapOperator.Object.<anonymous>.MapOperator.call (<user>/node_modules/rxjs/operator/map.js:54:23) } ]

输出:

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