0

我有一个包含两列的表:k 是键,a 可能包含空值。一个例子如下:

drop table if exists test;
create table test(k, a) as
select * from ( values
(1, 1),
(2, 2),
(3, 3),
(4, NULL),
(5, NULL),
(6, 6),
(7, 7),
(8, NULL),
(9, 9),
(10, 10)
) t;

我需要将按列 k 排序的列 a 的值聚合到几个没有空值的数组中。使用 array_agg 和过滤器不是我需要的

select array_agg(a order by k)  from test
-- "{1,2,3,NULL,NULL,6,7,NULL,9,10}"

select array_agg(a order by k) filter (where a is not null) from test
-- "{1,2,3,6,7,9,10}"

我需要获得的内容如下

"{1,2,3}"
"{6,7}"
"{9,10}"

知道如何实现这一目标吗?

4

2 回答 2

1

You can define the groups by counting the number of NULL values up-to-each row. The rest is then just filtering and aggregation:

select array_agg(k order by a)
from (select t.*,
             count(*) filter (where a is null) over (order by k) as grp
      from test t
     ) t
where a is not null
group by grp;

Here is a db<>fiddle.

于 2019-12-27T02:56:32.570 回答
0

string_to_array也许和的某种组合regexp_split_to_table可能会起作用:

postgres=# select string_to_array(trim(both ',' from arr),',') as sta from (select regexp_split_to_table(array_to_String(array_agg(a order by k),',','*'),'\*') as arr from test) as foo where foo.arr <> ',';
   sta   
---------
 {1,2,3}
 {6,7}
 {9,10}
(3 rows)
于 2019-12-27T02:22:38.627 回答