将两列和两行聚合为一

Aggregate two columns and rows into one

我有以下 table 结构

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]

顺便说一句,我正在使用 Postgres

一种方法是对它们进行逆透视然后聚合:

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;

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

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

如果顺序很重要,您可以使用 Gordon's 方法 但是 :

  • 添加聚合订单array_agg(d order by d ASC)
  • 使用unnest而不是union all,因为戈登的解决方案(union all)进行了两次序列扫描。如果 table 很大,使用性能会更好:

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

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

我假设startend字符类型

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