使用窗口函数array_agg
将一列减少为一个数组。
create table names (
last_name varchar,
first_name varchar
);
insert into names
(last_name, first_name)
values
('waterman', 'tom'),
('waterman', 'alex'),
('waterman', 'david'),
('barnett', 'rebecca'),
('barnett', 'anne');
select
last_name,
array_agg(first_name) over (partition by last_name) first_names
from names;
上面的查询产生以下结果:
LAST_NAME FIRST_NAMES
waterman ["tom", "alex", "david" ]
waterman ["tom", "alex", "david" ]
waterman ["tom", "alex", "david" ]
barnett ["rebecca", "anne" ]
barnett ["rebecca", "anne" ]
然后,您可以使用运算符将其减少为唯一的last_name
,first_name
对distinct
。
select
distinct
last_name,
array_agg(first_name) over (partition by last_name) first_names
from names;
要将返回的值数组转换array_agg
为 JSON,您可以简单地使用::variant
.
select
distinct
last_name,
array_agg(first_name) over (partition by last_name)::variant first_names
from names;