繁体   English   中英

根据列的字符串长度将行拆分为多行 Postgresql

[英]Split rows into multiple rows based on string length of column Postgresql

我有下表

+---------------+---------------+-------------+
| employee_name |     role      | date_joined |
+---------------+---------------+-------------+
| John          |      10013004 | 2018-01-09  |
| Jane          |          1004 | 2020-08-09  |
| Sam           |  100380003000 | 2022-03-31  |
+---------------+---------------+-------------+

我想将上表转换为以下格式,其中角色列字符串应分成 4 组,并应添加为新条目。

+---------------+-------+-------------+
| employee_name | role  | date_joined |
+---------------+-------+-------------+
| John          |  1001 | 2018-01-09  |
| John          |  3004 | 2018-01-09  |
| Jane          |  1004 | 2020-08-09  |
| Sam           |  1003 | 2022-03-31  |
| Sam           |  8000 | 2022-03-31  |
| Sam           |  3000 | 2022-03-31  |
+---------------+-------+-------------+

知道如何实现以下目标吗?

您可以使用regexp_matches()生成包含这 4 个字符子字符串的行:

select t.employee_name,
       x.role[1] as role,
       x.pos,
       t.date_joined
from the_table t
  cross join regexp_matches(t.role, '[0-9]{4}', 'g') with ordinality as x(role, pos)       
order by t.employee_name, t.date_joined

regexp_matches()返回一个匹配数组,这就是为什么需要x.role[1]的原因。

如果该列可以包含其他字符,而不仅仅是数字,请使用'.{4}'而不是'[0-9]{4}'

在线示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM