【发布时间】:2021-08-04 07:24:03
【问题描述】:
这里我有一个 JSON 字段,我想在每个 id 上选择第二高到最低的记录 数据是
JSON 看起来像这样
{
"user": [
{
"user_name": "Devang",
"user_weight": 0.7676846955248864
},
{
"user_name": "Meet",
"user_weight": 1.1021
},
{
"user_name": "Devang",
"user_weight": 0.16163873153859706
},
{
"user_name": "Rajan",
"user_weight": 0.22163873153859706
}
],
"address": [
{
"address_name": "India"
}
]
}
我执行的查询是
WITH cte AS (
SELECT id, ('{user,'||index-1||'}')::text[] as json_path, value->'user_weight'
FROM user_table, jsonb_array_elements(json_field->'user')
WITH ordinality arr(value, index) WHERE arr.value->>'user_name' IN ('Devang', 'Meet') order by id, value->'user_weight' DESC
) select * from cte;
获得这种记录
id json_path ?column?
1 {user,1} 1.1021
1 {user,0} 0.7676846955248864
1 {user,2} 0.16163873153859706
2 {user,0} 0.7676846955248864
2 {user,1} 0.07447325861051013
我想要这样的第二高到最低的记录
id json_path ?column?
1 {user,1} 1.1021 # this is the highest one in 1 id so I do not need this
1 {user,0} 0.7676846955248864
1 {user,2} 0.16163873153859706
2 {user,0} 0.7676846955248864 # this is the highest one in 2 ids so. I do not want
2 {user,1} 0.07447325861051013
输出是
id json_path ?column?
1 {user,0} 0.7676846955248864
1 {user,2} 0.16163873153859706
2 {user,1} 0.07447325861051013
看这里Demo
任何答案将不胜感激
【问题讨论】:
标签: sql postgresql common-table-expression jsonb