我有查询从这样的表中得到结果:
SELECT test_id, content::json->'scenario'
FROM test
我得到了这些结果,方案列中的对象数组:
test_id | scenario
29 | [{"name":"OpenSignal", "task":[{"name":"speedtest"}]}, {"name":"ITest", "task":[{"name":"speedtest"}]}, {"name":"EqualOne", "task":[{"name":"flashtest"}, {"name":"web"}, {"name":"video"}]}]
30 | [{"name":"Speedtest", "task":[{"name":"speedtest"}]}, {"name":"ITest", "task":[{"name":"speedtest"}]}, {"name":"EqualOne", "task":[{"name":"flashtest"}, {"name":"web"}, {"name":"video"}]}]
对象结构如下:
[{
"name": "OpenSignal",
"task": [{
"name": "speedtest"
}]
}, {
"name": "ITest",
"task": [{
"name": "speedtest"
}]
}, {
"name": "EqualOne",
"task": [{
"name": "flashtest"
}, {
"name": "web"
}, {
"name": "video"
}]
}]
我怎样才能得到这样的结果:
test_id | scenario
29 | Opensignal-speedtest
29 | ITest-speedtest
29 | EqualOne-flashtest
29 | EqualOne-web
29 | EqualOne-video
30 | Opensignal-speedtest
30 | ITest-speedtest
30 | EqualOne-flashtest
30 | EqualOne-web
30 | EqualOne-video
和
test_id | scenarios
29 | OpenSignal-speedtest,ITest-speedtest,EqualOne-flashtest, EqualOne-web,EqualOne-video
30 | Speedtest-speedtest,ITest-speedtest,EqualOne-flashtest,EqualOne-web,EqualOne-video
先谢谢我的兄弟们
答案 0 :(得分:2)
对于您的第一个查询,您可以执行以下操作:
SELECT test_id, CONCAT(sub.element->'name', '-', json_array_elements(sub.element->'task')->'name') as scenario
FROM
(SELECT test_id, json_array_elements(content::json) as element
FROM test) as sub;
我使用子查询从原始json中获取元素,然后使用短划线将每个任务名称连接起来。
然后,为了轻松地将它们按id分隔,我使用string_agg函数将其包装在另一个子查询中:
SELECT test_id,
string_agg(task, ',')
FROM(
SELECT test_id, CONCAT(sub.element->'name', '-', json_array_elements(sub.element->'task')->'name') as task
FROM
(SELECT test_id, json_array_elements(content::json) as element
FROM test) as sub
)as tasks
GROUP BY test_id
很抱歉,如果它看起来有点乱,这里有一个你可以使用的sqlfiddle链接。 http://sqlfiddle.com/#!17/fcb27/38