如果连续日期和不同范围的日期范围显示为日期和最大日期,如果序列有中断

时间:2017-01-07 19:51:49

标签: mysql

假设一张桌子有候选人的考试通过日期,我现在想要显示候选人已经过去的结束日期作为范围

表1

Person.              year
11.                    1-1- 2013
11.                     1-1-2014
11.                     1-1-2015
11.                     1-1-2017
11.                     1-1-2018
11.                     1-1-2020

现在我要整理序列并像这样显示

11                    1-1-2013  1-1-2015
11.                   1-1-2017  1-1-2018
11.                   1-1-2020

如何在sql中执行此操作

1 个答案:

答案 0 :(得分:1)

你可以使用这样的查询来获得你想要的结果,但它不是最好的代码:

SELECT person, 
    CONCAT (
        MIN( myyear),
         IF( MIN(myyear) = MAX(myyear) ,'', CONCAT('    ',MAX(myyear)) )
    )  AS `year`
FROM (
    SELECT
        e.*
        , @grp := if(YEAR(@last_year)+1 = YEAR(e.myyear), @grp, @grp+1) as grp
        , @last_year := e.myyear as tmp
    FROM exam e
    CROSS JOIN ( SELECT @grp :=0, @ast_year:=0) AS init
    ORDER BY person,myyear
    ) as result
group by grp;


**sample table**

mysql> SELECT * FROM exam;
+----+--------+------------+
| id | person | myyear     |
+----+--------+------------+
|  1 |     11 | 2013-01-01 |
|  2 |     11 | 2014-01-01 |
|  3 |     11 | 2015-01-01 |
|  4 |     11 | 2017-01-01 |
|  5 |     11 | 2018-01-01 |
|  6 |     11 | 2020-01-01 |
+----+--------+------------+
6 rows in set (0,00 sec)

示例查询

mysql> SELECT person,
    ->     CONCAT (
    ->         MIN( myyear),
    ->          IF( MIN(myyear) = MAX(myyear) ,'', CONCAT('    ',MAX(myyear)) )
    ->     )  AS `year`
    -> FROM (
    ->     SELECT
    ->         e.*
    ->         , @grp := if(YEAR(@last_year)+1 = YEAR(e.myyear), @grp, @grp+1) as grp
    ->         , @last_year := e.myyear as tmp
    ->     FROM exam e
    ->     CROSS JOIN ( SELECT @grp :=0, @ast_year:=0) AS init
    ->     ORDER BY person,myyear
    ->     ) as result
    -> group by grp;
+--------+--------------------------+
| person | year                     |
+--------+--------------------------+
|     11 | 2013-01-01    2015-01-01 |
|     11 | 2017-01-01    2018-01-01 |
|     11 | 2020-01-01               |
+--------+--------------------------+
3 rows in set (0,00 sec)

mysql>