[英]mysql group_concat only if consecutive dates
I have a table with a date field. 我有一个带有日期字段的表。 I need a query to group_concat the dates only if they are consecutive, otherwise return them individually.
仅当日期是连续的时,我才需要查询group_concat,否则单独返回它们。
So, for example , if my table has the following data: 因此,例如,如果我的表具有以下数据:
+---------+--------------+
| user_id | checkin_date |
+---------+--------------+
| 1 | 2012-02-01 |
| 2 | 2012-03-01 |
| 3 | 2012-02-03 |
| 4 | 2012-02-02 |
+---------+--------------+
I need a query that would return the following results 我需要一个查询,该查询将返回以下结果
+--------------------------+
| checkin_period |
+--------------------------+
| 2012-02-01 - 2012-02-03 |
| 2012-03-01 |
+--------------------------+
As you can see, feb 1st, 2nd and 3rd have been grouped in 1 row (with only the first and last day being displayed), whereas March 1st is by itself... 如您所见,2月1日,2日和3日已分组为一排(仅显示第一天和最后一天),而3月1日本身就是...
I have no idea where to start! 我不知道从哪里开始!
Thanks in advance, 提前致谢,
Alain 阿兰
You could increment a user variable @p
only if the checkin_date is not consecutive with the prior row, that is if the date increases by more than 1 day. 仅当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 |
+------+------------+
Then use the above as a subquery, grouping by the p
column, and return a string of the min to max range or else just one value if the count within the group is 1. 然后将上面的内容用作子查询,按
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 |
+-------------------------+
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.