Mysql将列字符串拆分为三行

时间:2016-11-11 13:37:50

标签: mysql sql

此查询

SELECT user_Id,CAST(leave_dates_object AS CHAR(10000) CHARACTER SET utf8) AS LeaveDates 
FROM `lms_leaves` 

返回

enter image description here

现在我想要三行user_Id,并且格式化字符串中的Date和F_or_H从请假日期返回。

我修改并尝试code from this link但无法获得结果。

预期产出

user_Id Date    LeaveType
85  2016-09-06  F
85  2016-09-07  F
85  2016-09-06  H
63  2016-03-25  F
63  2016-03-02  F
63  2016-03-03  H

请帮帮我。

1 个答案:

答案 0 :(得分:2)

假设您在一条记录中最多有8个日期:

create table users (userId int not null, leaveDates varchar(1000) not null);

INSERT users (userId,leaveDates) VALUES (85,'--- \r-2016-09-06:F\r-2016-09-07:F'),(85,'---\r-2016-09-06:H'),(63,'---\r-2016-03-25:F'),(63,'---\r-2016-03-02:F\r-2016-03-03:H');

SELECT s.userId AS userId,LEFT(s.leaveDate,CHAR_LENGTH(s.leaveDate)-2) AS ldate, RIGHT(s.leaveDate,1) AS lflag
FROM (
  SELECT 
    u.userId, 
      REPLACE(SUBSTRING(SUBSTRING_INDEX(u.leaveDates, '\r-', n.number),
         CHAR_LENGTH(SUBSTRING_INDEX(u.leaveDates, '\r-', n.number -1)) + 1),
         '\r-', '') as leaveDate
  FROM (SELECT u0.userId,REPLACE(u0.leaveDates,'---','') AS leaveDates FROM users u0) u
  INNER JOIN (SELECT 1 AS number UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8) n
  ON (char_length(u.leaveDates) - char_length(replace(u.leaveDates, '\r-', '')) >= n.number-1)) s
 WHERE s.leaveDate<>''
 ORDER BY userId,ldate,lflag;