postgres 行列转换

行转列

imos=# create table test_split_to_table(id int, name_list varchar);
CREATE TABLE
imos=# insert into test_split_to_table values(1,'a;b;c'),(2,'d;e;f');
INSERT 0 2
imos=#
imos=# select * from test_split_to_table ;
 id | name_list
----+-----------
  1 | a;b;c
  2 | d;e;f
(2 rows)

imos=#
imos=#
imos=# select id, regexp_split_to_table(name_list,';') from test_split_to_table ;
 id | regexp_split_to_table
----+-----------------------
  1 | a
  1 | b
  1 | c
  2 | d
  2 | e
  2 | f
(6 rows)

列转行

imos=# create temp table test_column_to_row as select id, regexp_split_to_table(name_list,';') from test_split_to_table ;
SELECT 6
imos=# select * from test_column_to_row ;
 id | regexp_split_to_table
----+-----------------------
  1 | a
  1 | b
  1 | c
  2 | d
  2 | e
  2 | f
(6 rows)

imos=# select id, string_agg(regexp_split_to_table,';') from test_column_to_row  group by id;
 id | string_agg
----+------------
  1 | a;b;c
  2 | d;e;f
(2 rows)

原文地址:https://www.cnblogs.com/yldf/p/11899975.html