背景:把接收人[JSRID]拆分为多行,接收人是存在一个字段中,以逗号隔开,每次会议的接收人数量不一
建表语句:
CREATE TABLE "HYTZGGZS_HYTZGGXXTJ" (
"WF_ORUNID" VARCHAR2(255 BYTE) VISIBLE,
"WF_DOCCREATED" VARCHAR2(255 BYTE) VISIBLE,
"HYMC" VARCHAR2(255 BYTE) VISIBLE,
"HYDD" VARCHAR2(255 BYTE) VISIBLE,
"HYKSSJ" VARCHAR2(255 BYTE) VISIBLE,
"HYJSSJ" VARCHAR2(255 BYTE) VISIBLE,
"JSRID" VARCHAR2(255 BYTE) VISIBLE
);
测试数据:
INSERT INTO "HYTZGGZS_HYTZGGXXTJ" ("WF_ORUNID", "WF_DOCCREATED", "HYMC", "HYDD", "HYKSSJ", "HYJSSJ", "JSRID") VALUES ('fec65a570c0be04ecf0b2140a74d7e2fd646', '2023-06-05 21:19', '测试会议1', '第一会议室', '2023-06-05 08:30', '2023-06-06 11:16', '123432,123003,123005,123007,123008,123013,620040,123010,123020,123150,123177,123211,123043,123429,123411,123059,123426,123031,123178,123412,123326,123016,123393,123030,123212,123247,123149,123080');
INSERT INTO "HYTZGGZS_HYTZGGXXTJ" ("WF_ORUNID", "WF_DOCCREATED", "HYMC", "HYDD", "HYKSSJ", "HYJSSJ", "JSRID") VALUES ('8f3049c80a9dd0424c08336017de5ae03eb4', '2023-06-07 11:00', '测试会议2', '第二会议室', '2023-06-07 15:00', '2023-06-07 15:59', '123010,123150,123059,123016,123080,123327,123428,123412,123032');
INSERT INTO "HYTZGGZS_HYTZGGXXTJ" ("WF_ORUNID", "WF_DOCCREATED", "HYMC", "HYDD", "HYKSSJ", "HYJSSJ", "JSRID") VALUES ('e80e42820c5760411d09e140403cacd361ac', '2023-06-10 09:08', '测试会议3', '第三会议室', '2023-06-12 14:30', '2023-06-12 15:30', '123432,123003,123005,123006,123007,123008,123013,123051,620040,123010,123150,123429,123043,123431,123059,123426,123031,123178,123412,123020,123211,123149,123247,123393,123326,123016');
INSERT INTO "HYTZGGZS_HYTZGGXXTJ" ("WF_ORUNID", "WF_DOCCREATED", "HYMC", "HYDD", "HYKSSJ", "HYJSSJ", "JSRID") VALUES ('ec1843d205468046e20bb3d0485cbf8f6a82', '2023-06-13 15:25', '测试会议4', '第四会议室', '2023-06-14 14:30', '2023-06-14 15:23', '123010,123020,123177,123211,123248,123022,123149,123247,123394,123393,123380,123326,123412');
INSERT INTO "HYTZGGZS_HYTZGGXXTJ" ("WF_ORUNID", "WF_DOCCREATED", "HYMC", "HYDD", "HYKSSJ", "HYJSSJ", "JSRID") VALUES ('3cde3c5c09cf40432d0bc0d007b5289c8603', '2023-06-14 08:25', '测试会议5', '第五会议室', '2023-06-14 16:30', '2023-06-14 17:25', '123010,123020,123177,123211,123248,123022,123149,123247,123394,123393,123380,123326,123412');
预期结果:
解决方法:
使用递归查询(Recursive Subquery):
首先,初始查询从源表中选择第一个接收人,并赋予一个行号(RN)。然后,递归部分将从上一行的行号开始查找下一个接收人,并继续增加行号。递归过程会一直执行,直到没有更多的接收人可以拆分。
sql如下:
WITH CTE (WF_ORUNID, HYMC, HYDD, HYKSSJ, HYJSSJ, JSRID, SSYH, RN) AS (
SELECT WF_ORUNID, HYMC, HYDD, HYKSSJ, HYJSSJ, JSRID,
REGEXP_SUBSTR(JSRID, '[^,]+', 1, 1) AS SSYH,
1 AS RN
FROM HYTZGGZS_HYTZGGXXTJ
UNION ALL
SELECT WF_ORUNID, HYMC, HYDD, HYKSSJ, HYJSSJ, JSRID,
REGEXP_SUBSTR(JSRID, '[^,]+', 1, RN + 1) AS SSYH,
RN + 1 AS RN
FROM CTE
WHERE REGEXP_SUBSTR(JSRID, '[^,]+', 1, RN + 1) IS NOT NULL
)
SELECT WF_ORUNID, HYMC, HYDD, HYKSSJ, HYJSSJ, SSYH
FROM CTE
ORDER BY WF_ORUNID, RN;