我的表格如下:
╔═════╦═════════════════════╦═════════════════════╦═════════════╗
║ id ║ begin ║ end ║ employeesId ║
╠═════╬═════════════════════╬═════════════════════╬═════════════╣
║ 4 ║ 2015-11-11 00:00:00 ║ 2015-11-11 09:00:00 ║ 8 ║
║ 80 ║ 2015-11-11 09:00:00 ║ 2015-11-11 12:00:00 ║ 8 ║
║ 49 ║ 2015-11-11 00:00:00 ║ 2015-11-11 08:00:00 ║ 61 ║
║ 32 ║ 2015-11-11 08:00:00 ║ 2015-11-12 06:00:00 ║ 61 ║
║ 42 ║ 2015-11-12 07:00:00 ║ 2015-11-12 13:00:00 ║ 61 ║
║ 17 ║ 2015-11-11 00:00:00 ║ 2015-11-11 08:00:00 ║ 22 ║
║ 42 ║ 2015-11-11 09:00:00 ║ 2015-11-11 12:00:00 ║ 22 ║
╚═════╩═════════════════════╩═════════════════════╩═════════════╝
我想合并列employeesId
相等的行,并且一行的begin
时间等于另一行的end
时间。像这样:
╔═════════════════════╦═════════════════════╦═════════════╗
║ begin ║ end ║ employeesId ║
╠═════════════════════╬═════════════════════╬═════════════╣
║ 2015-11-11 00:00:00 ║ 2015-11-11 12:00:00 ║ 8 ║
║ 2015-11-11 00:00:00 ║ 2015-11-12 06:00:00 ║ 61 ║
║ 2015-11-12 07:00:00 ║ 2015-11-12 13:00:00 ║ 61 ║
║ 2015-11-11 00:00:00 ║ 2015-11-11 08:00:00 ║ 22 ║
║ 2015-11-11 09:00:00 ║ 2015-11-11 12:00:00 ║ 22 ║
╚═════════════════════╩═════════════════════╩═════════════╝
编辑:
我需要合并连续的日期时间,在这个例子中你可以看到结束时间'2015-11-11 12:00:00'为employeesId = 8替换结束时间'2015-11-11 09:00:00'在第一行,因为第二行的开头等于第一行的结尾。
答案 0 :(得分:2)
Try join
SELECT a.`begin_date`, IF(b.`end_date` IS NOT NULL, b.`end_date`, a.`end_date`), a.`employer_id`
FROM `mytable` a
LEFT JOIN `mytable` b ON a.`employer_id` = b.`employer_id` AND a.`end_date` = b.`begin_date`
LEFT JOIN `mytable` c ON a.`employer_id` = c.`employer_id` AND a.`begin_date` = c.`end_date`
WHERE c.`id` IS NULL
But you should rebuild your schema.
答案 1 :(得分:0)
You can use MIN(),MAX()
if you want to get earlier and later times.
SELECT MIN(begin),MAX(end),employeesId
FROM table_name
GROUP BY employeesId
Hope this helps