我正在查询的表如下所示:

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

我想这样把它从数据库中取出:
{
    "foo": {
        "bar": "baz",
        "alpha": "beta"
    },
    "gamma": {
        "delta": "epsilon"
    }
}

json_object_agg并不能真正让我通过第一级,因为你不允许嵌套聚合函数。但据我所见,我需要一个GROUP BY内的GROUP BY,但我不确定是否有可能。或许解决方案与WINDOWs有关?

最佳答案

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" } }

由于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

关于json - Postgres:嵌套聚合JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33528898/

10-10 23:59