我创建了一个带有json列的小表,我想像这样显示表中的所有名称:
id_test | test
---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------
1 | {"clients":{"nbr":"2","info":[{"nom":"med","genre":"male","age":"25"},{"nom":"aicha","genre":"female","age":"24"}]}}
3 | {"clients":{"nbr":"3","info":[{"nom":"yns","genre":"male","age":"23"},{"nom":"oussama","genre":"male","age":"24"},{"nom":"sara","genre":"female","age":"27"}]}}
2 | {"clients":{"nbr":"1","info":{"nom":"kenza","genre":"female","age":"26"}}}
所需的输出:
name
---------
med
aicha
yns
oussama
sara
kenza
我也想列出每种类型的性别数
所需的输出:
genre | count
--------+-------
female | 3
male | 3
答案 0 :(得分:0)
第一个查询:
SELECT
json_array_elements(CASE
WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
ELSE json_build_array(test->'clients'->'info')
END)->>'nom' AS name
FROM my_table;
第二个查询:
SELECT
json_array_elements(CASE
WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
ELSE json_build_array(test->'clients'->'info')
END)->>'genre' AS genre,
count(*)
FROM my_table
GROUP BY 1;