在PostgreSQL中按组嵌套JSON聚合行

时间:2019-07-02 07:40:29

标签: json postgresql group-by aggregate

我有一个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"]}

2 个答案:

答案 0 :(得分:2)

demo:db<>fiddle

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
  1. city对名称进行分组。要将name放入一个JSON数组中,可以使用聚合函数json_agg()
  2. 通过country将结果分组。要获得预期的输出,您需要使用聚合函数json_object_agg(),该函数根据cityname数组创建键/对值

documentation

答案 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;