gpt4 book ai didi

json - postgresql 中分组依据的嵌套 json 聚合行

转载 作者:行者123 更新时间:2023-11-29 12:07:15 24 4
gpt4 key购买 nike

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

最佳答案

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. 城市 对名称进行分组。要将 name 放入一个 JSON 数组中,您可以使用聚合函数 json_agg()
  2. 国家/地区 将此结果分组。要获得预期的输出,您需要使用聚合函数 json_object_agg(),它从 cityname 数组

documentation

关于json - postgresql 中分组依据的嵌套 json 聚合行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com