在 regexp_split_to_array 之后拆分字符

Splitting characters after regexp_split_to_array

select name, (regexp_split_to_array(name, '')) from table

结果是{a,b,c,d,e}。是否可以将其拆分为单独的行并按名称分组,使其看起来像:

a 1
b 2
c 3
d 4
e 5

您正在查找 unnest 函数:

select name, unnest(regexp_split_to_array(name, '')) from table

使用unnest() with row_number() window function:

WITH test_table(name) AS ( VALUES
  ('abcde')
)
SELECT *,row_number() OVER () AS row FROM (
  SELECT unnest(regexp_split_to_array(name,'')) AS name FROM test_table
) t;

结果:

 name | row 
------+-----
 a    |   1
 b    |   2
 c    |   3
 d    |   4
 e    |   5
(5 rows)

SO 也有很好的答案:

  • PostgreSQL unnest() with element number

如果您使用的是 9.4 或更高版本,则可以使用 with ordinality

SELECT name, u.*
FROM the_table
  cross join lateral unnest(regexp_split_to_array(name,'')) with ordinality as u(ch, nr)