简体   繁体   English

Postgres:嵌套聚合JSON

[英]Postgres: Nested Aggregate JSON

The table I'm querying looks like this: 我要查询的表如下所示:

namespace | key   | value
---------------------------
foo       | bar   | baz
foo       | alpha | beta
gamma     | delta | epsilon

And I'd like to pull it out of the database like this: 我想这样将其从数据库中拉出:

{
    "foo": {
        "bar": "baz",
        "alpha": "beta"
    },
    "gamma": {
        "delta": "epsilon"
    }
}

Playing around with json_object_agg isn't really getting me past the first level, since you're not allowed to nest aggregate functions. json_object_agg并不能真正使我超越第一级,因为不允许您嵌套聚合函数。 But as far as I can see, I need a GROUP BY within a GROUP BY , but I'm not sure if that's possible. 但是据我所知,我需要在GROUP BY中使用GROUP BY ,但是我不确定是否可行。 Perhaps the solution has to do with WINDOW s? 也许解决方案与WINDOW

with t (namespace, key, value) as (
    values
    ('foo','bar','baz'),('foo','alpha','beta'),('gamma','delta','epsilon')
), s as (
    select namespace, json_object_agg(key, value) as joa
    from t
    group by namespace
)
select json_object_agg(namespace, joa)
from s
;
                                  json_object_agg                                   
------------------------------------------------------------------------------------
 { "foo" : { "bar" : "baz", "alpha" : "beta" }, "gamma" : { "delta" : "epsilon" } }

As a CTE is an optimization barrier this version might be faster: 由于CTE是优化障碍,因此该版本可能会更快:

with t (namespace, key, value) as (
    values
    ('foo','bar','baz'),('foo','alpha','beta'),('gamma','delta','epsilon')
)
select json_object_agg(namespace, joa)
from (
    select namespace, json_object_agg(key, value) as joa
    from t
    group by namespace
) s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM