我想选择每个宠物品种的数量,并按其主人和类型分组。
我编写了一个子查询,它按宠物类型返回品种计数,这几乎是我所需要的,只是我需要 json 数组中的结果。
按类型分类 |
---|
{“type”:“CAT”,“breed_count”:[{“孟加拉”:1,“缅甸”:2}]} |
{"type": "DUG", "breed_count": [{"GERMAN_SHEPHERD": 1, "AKITA": 2}]} |
我预计 json_agg() 函数会执行此操作,但它返回一个错误:[21000] ERROR: more more row returned by a subquery using as an expression.
这是我的完整查询:
SELECT
o.id,
JSON_AGG(
(
SELECT
JSONB_BUILD_OBJECT(
'type',
p1.type,
'breed_count',
JSONB_BUILD_ARRAY(
JSONB_OBJECT_AGG(
p1.breed,
(
SELECT
COUNT(p2.id)
FROM
pet p2
WHERE
p2.owner_id = p1.owner_id
AND p2.breed = p1.breed
AND p2.type = p1.type
)
)
)
) AS breed_by_type
FROM
pet p1
GROUP BY
p1.type
)
)
FROM
owner o
JOIN pet p ON p.owner_id = o.id
GROUP BY
o.id;
如何将子查询的结果收集到json数组中?
示例:d-fiddle
这是另一种更优化的选择:
select jsonb_build_object(
'type',
type,
'breed_count',
json_agg(jsonb_build_object(breed, cnt))
) as breed_by_type
from (
select type, breed, count(*) as cnt
from pet
group by type, breed
) as s
group by type;
结果:
breed_by_type
--------------
{"type":"CAT","breed_count":[{"BURMESE":2},{"BENGAl":1}]}
{"type":"DOG","breed_count":[{"AKITA":2},{"GERMAN_SHEPHERD":1}]}