postgresql 行列互转函数

关系型数据库的行列转换函数在实际应用中是相当普遍。postgresql 作为一款优秀的开源数据库,提供相关的转换函数是必须的。

列=》行

使用 string_agg 函数

with tmp_t0 as (
    select 'A'::varchar as c1 union all
    select 'B'::varchar as c1 union all
    select 'C'::varchar as c1 
)
select string_agg(c1,',') 
  from tmp_t0
  ; 

 string_agg 
------------
 A,B,C
(1 row)

使用 array_agg 函数

with tmp_t0 as (
    select 'A'::varchar as c1 union all
    select 'B'::varchar as c1 union all
    select 'C'::varchar as c1 
)
select array_agg(c1) 
  from tmp_t0
  ; 

 array_agg 
-----------
 {A,B,C}
(1 row)

行=》列

使用regexp_split_to_table函数

with tmp_t0 as (
    select 'A,B,C,D'::varchar as c1 
)
select regexp_split_to_table(c1,',') 
  from tmp_t0
  ;

 regexp_split_to_table 
-----------------------
 A
 B
 C
 D
(4 rows)

参考:
https://www.postgresql.org/docs/9.6/static/functions-aggregate.html
https://www.postgresql.org/docs/9.6/static/functions-string.html

posted @ 2018-06-15 09:51  peiybpeiyb  阅读(1582)  评论(0编辑  收藏  举报