[英]MySQL, group by two different columns
My table looks like: 我的表看起来像:
╔═════╦═════════════════════╦═════════════════════╦═════════════╗
║ 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 ║
╚═════╩═════════════════════╩═════════════════════╩═════════════╝
I want to merge rows where columns employeesId
are equal, and begin
time of one row is equal to end
time of another row. 我想合并其中
employeesId
列相等的行,并且一行的begin
时间等于另一行的end
时间。 Like this: 像这样:
╔═════════════════════╦═════════════════════╦═════════════╗
║ 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 ║
╚═════════════════════╩═════════════════════╩═════════════╝
edit: 编辑:
I need to merge continuous datetimes, in this example you can see that end time '2015-11-11 12:00:00' for employeesId = 8 replaced end time '2015-11-11 09:00:00' in first row because begin of the second row is equal to end of the first row.
我需要合并连续的日期时间,在这个例子中,您可以看到employeeId = 8的结束时间'2015-11-11 12:00:00'替换了第一行的结束时间'2015-11-11 09:00:00'因为第二行的开头等于第一行的结尾。
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. 但是你应该重建你的架构。
You can use MIN(),MAX()
if you want to get earlier and later times. 如果想要更早和更晚的时间
MIN(),MAX()
可以使用MIN(),MAX()
。
SELECT MIN(begin),MAX(end),employeesId
FROM table_name
GROUP BY employeesId
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.