在postgres数组中解压缩记录

时间:2017-05-15 17:24:26

标签: postgresql

给定下面定义的t_my_type和数组打包和解包:

create type t_my_type as (aa TEXT, bb INTEGER);

with q0 as (
  select 'a' x, 1 y UNION
  select 'b' x, 2 y
),
q1 as (
    select array_agg(distinct(x,y)::t_my_type) a from q0 q
),
q2 as (
    SELECT unnest(q1.a) a from q1
)
SELECT (q.a::t_my_type).aa, (q.a::t_my_type).bb
from q2 q
;

我想知道是否有 最后一个查询的更优雅(更少数量的演员阵容):

SELECT q.aa, q.bb

而不是

SELECT (q.a::t_my_type).aa, (q.a::t_my_type).bb

2 个答案:

答案 0 :(得分:2)

with q0 as (
  select 'a' x, 1 y union
  select 'b' x, 2 y
),
q1 as (
    select array_agg(distinct(x,y)::t_my_type) a from q0 q
),
q2 as (
    select unnest(q1.a) a from q1
)

select (a).*
from q2;

 aa | bb 
----+----
 a  |  1
 b  |  2
(2 rows)

当然,您也可以明确指定列

select (a).aa, (a).bb
from q2;

答案 1 :(得分:0)

这里我用值替换union并跳过聚合/取消:

t=# with a(t_my_type) as (
  values (('a',2)::t_my_type),(('b',1)::t_my_type)
)
select (t_my_type).*
from a;
 aa | bb
----+----
 a  |  2
 b  |  1
(2 rows)