我有一个Postgresql表
alok=# select * from people;
name | country | city
---------+---------+---------
alok | india | delhi
ram | india | kolkata
shyam | india | kanpur
krishna | us | newyork
ajit | india | delhi
sami | india | delhi
mohamad | india | kolkata
(7 rows)
可以由
生成create table people(name varchar, country varchar, city varchar);
insert into people values('alok', 'india', 'delhi');
insert into people values('ram', 'india', 'kolkata');
insert into people values('shyam', 'india', 'kanpur');
insert into people values('krishna', 'us', 'newyork');
insert into people values('ajit', 'india', 'delhi');
insert into people values('sami', 'india', 'delhi');
insert into people values('mohamad', 'india', 'kolkata');
我想在国家和城市上生成汇总名称,例如
country | name
---------+------------------------------------
india | {"delhi":["alok", "ajit", "sami"], "kolkata":["ram", "mohamad"], "kanpur":["shyam"]}
us | {"newyork":["krishna"]}
答案 0 :(得分:2)
SELECT
country,
json_object_agg(city, agg_names)
FROM (
SELECT
country,
city,
json_agg(name) AS agg_names
FROM
people
GROUP BY country, city
) s
GROUP BY country
city
对名称进行分组。要将name
放入一个JSON数组中,可以使用聚合函数json_agg()
country
将结果分组。要获得预期的输出,您需要使用聚合函数json_object_agg()
,该函数根据city
和name
数组创建键/对值答案 1 :(得分:0)
select
country, json_agg( json_build_object( 'city', city, 'name', name ) )
from (
select country, city, json_agg( name ) as name
from people
group by country, city
) a
group by a.country;