我查询的表格如下:
Spring boot
我想将它从数据库中拉出来:
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
s?
答案 0 :(得分:2)
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