将两列和一行聚合为一列

时间:2015-10-21 10:49:35

标签: sql postgresql aggregate-functions aggregate

我有以下表结构

start|end
09:00|11:00
13:00|14:00

我知道

SELECT ARRAY_AGG(start), ARRAY_AGG(end)

将导致

start|end
[09:00,13:00]|[11:00,14:00]

但我怎样才能得到以下结果? 结果

[09:00,11:00,13:00,14:00]

BTW,我正在使用Postgres

3 个答案:

答案 0 :(得分:2)

您可以进行数组连接(如果顺序不重要):

SELECT ARRAY_AGG(start) || ARRAY_AGG(end) FROM TABLE1

如果订单很重要,您可以使用Gordon's方法,但

  • 添加汇总订单array_agg(d order by d ASC)
  • 使用unnest代替union all,因为Gordon的解决方案(union all)执行两次序列扫描。如果表很大,那么使用性能会更好:

    SELECT array_agg(d ORDER BY d ASC) FROM(
        SELECT unnest(ARRAY[start] || ARRAY[end]) as d from table1
    ) sub
    

在表上只执行一次序列扫描(并且会更快)。

答案 1 :(得分:1)

一种方法是取消它们然后聚合:

select array_agg(d)
from (select start as d from t
      union all
      select end as d from t
     ) t;

类似的方法使用cross join

select array_agg(case when n.n = 1 then t.start else t.end end)
from t cross join
     (select 1 as n union all select 2) n;

答案 2 :(得分:0)

我认为startend字符类型

select ARRAY_AGG(col) 
from(select string_agg(strt::text||','||en::text,',') col 
     from b
)t