mysql group_concat仅在连续日期时才有

时间:2014-02-13 20:45:08

标签: mysql group-concat

我有一个带有日期字段的表。我需要查询group_concat日期,只有它们是连续的,否则单独返回它们。

因此,例如,如果我的表具有以下数据:

+---------+--------------+
| user_id | checkin_date |
+---------+--------------+
|       1 | 2012-02-01   |
|       2 | 2012-03-01   |
|       3 | 2012-02-03   |
|       4 | 2012-02-02   |
+---------+--------------+

我需要一个返回以下结果的查询

+--------------------------+
| checkin_period           |
+--------------------------+
| 2012-02-01 - 2012-02-03  |
| 2012-03-01               |
+--------------------------+

正如你所看到的,第1代,第2代和第3代被分为1行(仅显示第一天和最后一天),而3月1日本身就是......

我不知道从哪里开始!

提前致谢,

阿兰

2 个答案:

答案 0 :(得分:1)

只有当checkin_date与前一行不连续时,即只要日期增加超过1天,您才可以增加用户变量@p

SELECT IF(checkin_date <= @d + INTERVAL 1 DAY, @p, @p:=@p+1) AS p, @d:=checkin_date AS d
FROM (SELECT @p:=0, @d:='1900-01-01') _init, mytable 
ORDER BY checkin_date;

+------+------------+
| p    | d          |
+------+------------+
|    1 | 2012-02-01 |
|    1 | 2012-02-02 |
|    1 | 2012-02-03 |
|    2 | 2012-03-01 |
+------+------------+

然后使用上面的子查询,按p列进行分组,并返回min到max范围的字符串,如果组内的计数为1,则只返回一个值。

SELECT IF(COUNT(*) > 1, CONCAT(MIN(d), ' - ', MAX(d)), MAX(d)) AS date_range 
FROM (
  SELECT IF(checkin_date <= @d + INTERVAL 1 DAY, @p, @p:=@p+1) AS p, @d:=checkin_date AS d
  FROM (SELECT @p:=0, @d:='1900-01-01') _init, mytable 
  ORDER BY checkin_date) AS t 
GROUP BY p;

+-------------------------+
| date_range              |
+-------------------------+
| 2012-02-01 - 2012-02-03 |
| 2012-03-01              |
+-------------------------+

答案 1 :(得分:1)

SELECT
  CONCAT_WS(' - ',
    MIN(checkin_date),
    CASE WHEN MAX(checkin_date)>MIN(checkin_date) THEN MAX(checkin_date) END
  ) As time_interval
FROM (
  SELECT
    CASE WHEN checkin_date=@last_ci+INTERVAL 1 DAY THEN @n ELSE @n:=@n+1 END AS g,
    @last_ci := checkin_date As checkin_date
  FROM
    tablename, (SELECT @n:=0) r
  ORDER BY
    checkin_date
) s
GROUP BY
  g

请参阅小提琴here