MySQL如何将GROUP_CONCAT拼接的打卡时间拆分为独立的多列
该需求完全可以实现,以下是两种常用实现方案:
方案1:MIN/MAX聚合实现(推荐,性能更优)
适用于每天仅2次打卡、上班为当天最早打卡、下班为当天最晚打卡的场景,无需拼接字符串再拆分:
SELECT t.emp_number AS id, t.date_created AS `date`, MIN(t.time_stamp) AS `in`, MAX(t.time_stamp) AS `out` FROM attendance_copy t WHERE t.attendance_status LIKE "%Punch%" -- 注意原SQL仅按日期分组,多个员工时数据会混乱,需同时按员工号+日期分组 GROUP BY t.emp_number, t.date_created ORDER BY t.emp_number, t.date_created;
注:in、date属于SQL保留字,作为字段别名时需要用反引号包裹避免语法报错。
方案2:字符串拆分实现
如果必须从拼接后的打卡字段拆分可使用该方案(以MySQL环境为例):
SELECT emp_number AS id, date_created AS `date`, -- 取第一个逗号前的内容作为上班时间 SUBSTRING_INDEX(punch, ',', 1) AS `in`, -- 取最后一个逗号后的内容作为下班时间 SUBSTRING_INDEX(punch, ',', -1) AS `out` FROM ( SELECT t.emp_number, t.date_created, -- 拼接时指定按时间戳排序,避免顺序混乱 GROUP_CONCAT(t.time_stamp ORDER BY t.time_stamp) as punch FROM attendance_copy t WHERE t.attendance_status LIKE "%Punch%" GROUP BY t.emp_number, t.date_created ) t ORDER BY id, `date`;
内容的提问来源于stack exchange,提问作者wenreloz
相关产品推荐
相关产品推荐

