Sql JSON对象键的逗号分隔列表
我的Postgres表中有一个varchar列,其值如下:Sql JSON对象键的逗号分隔列表,sql,json,database,postgresql,Sql,Json,Database,Postgresql,我的Postgres表中有一个varchar列,其值如下: { "vars": { "props": [{ "a": "testA1", "b": "testB1", "c": "testC1" }, { "a": null, "b": "testB2",
{
"vars": {
"props": [{
"a": "testA1",
"b": "testB1",
"c": "testC1"
},
{
"a": null,
"b": "testB2",
"c": "testB3"
}, {
"a": "testA3",
"b": "testB3",
"c": "testC3"
}
]
}
}
我想得到所有不为null的“a”键的列表,并用逗号分隔它们。应该是这样的:
{
"vars": {
"props": [{
"a": "testA1",
"b": "testB1",
"c": "testC1"
},
{
"a": null,
"b": "testB2",
"c": "testB3"
}, {
"a": "testA3",
"b": "testB3",
"c": "testC3"
}
]
}
}
testA1、testA3
实现这一点的最佳方法是什么?这里有一个选项,通过将字符串强制转换为jsonb数据类型,然后将
'props'
扩展到具有jsonb\u数组\u元素()
的行,过滤非空a
值并聚合:
select t.id, string_agg(j.v ->> 'a', ',') vals
from mytable t
cross join lateral jsonb_array_elements( (js::jsonb) -> 'vars' -> 'props') j(v)
where j.v ->> 'a' is not null
group by t.id
这假设您有一个主键或唯一列,可用于跟踪每个未列出的记录
:
with mytable as (
select 1 id, '{
"vars": {
"props": [
{
"a": "testA1",
"b": "testB1",
"c": "testC1"
},
{
"a": null,
"b": "testB2",
"c": "testB3"
}, {
"a": "testA3",
"b": "testB3",
"c": "testC3"
}
]
}
}' js
)
select t.id, string_agg(j.v ->> 'a', ',') vals
from mytable t
cross join lateral jsonb_array_elements( (js::jsonb) -> 'vars' -> 'props') j(v)
where j.v ->> 'a' is not null
group by t.id
id | VAL
-: | :------------
1 |测试1,测试3