我有一个由两级数组组成的json,如:
[
{
name: "Group one",
races:
[
{name: "Race 1"},
{name: "Race 2"},
]
},
{
name: "Group two",
races:
[
{name: "Race 10"},
{name: "Race 11"},
]
}
]
是否可以通过魔术SQL获得:
group_num | race_num | race
int | int | json
1 | 1 | {name: "Race 1"}
1 | 2 | {name: "Race 2"}
2 | 1 | {name: "Race 10"}
2 | 2 | {name: "Race 11"}
其中:
group_num
是其数组中每个组的排名race_num
是其数组中每个种族的等级我认为这可能与json_array_elements(json)
和row_number() OVER ()
有关,但我无法确定如何做到正确!
答案 0 :(得分:0)
with my_table(data) as (
values(
'[
{
"name": "Group one",
"races":
[
{"name": "Race 1"},
{"name": "Race 2"}
]
},
{
"name": "Group two",
"races":
[
{"name": "Race 10"},
{"name": "Race 11"}
]
}
]'::json)
)
select
group_num,
rank() over (partition by group_num order by value->>'name') as race_num,
value as race
from (
select
rank() over (order by value->>'name') as group_num,
value as grp
from my_table,
json_array_elements(data)
) s,
json_array_elements(grp->'races');
结果:
group_num | race_num | race
-----------+----------+---------------------
1 | 1 | {"name": "Race 1"}
1 | 2 | {"name": "Race 2"}
2 | 1 | {"name": "Race 10"}
2 | 2 | {"name": "Race 11"}
(4 rows)
注意,您的json无效,请使用jsonlint来验证json表达式。