postgresql - Can't sort by all array's items?
问题描述
Postgresq 9.6
json
"availability": [
{
"qty": 25,
"price": 1599,
"is_available": true
},
{
"qty": 72,
"price": 3599,
},
"is_available": true
]
table with column data. Type is jsonb
If I want to sort first array's(availability) item by field "price" I this:
SELECT *
from product prod
WHERE to_tsvector('english', prod.data) @@ to_tsquery('gram')
ORDER BY prod.data #> '{availability,0,price}' desc
OK.
But I need to sort all fields "price" in array availability
Smt like this (pseudo code)
SELECT *
from product prod
WHERE to_tsvector('english', prod.data) @@ to_tsquery('gram')
ORDER BY prod.data #> '{availability,*,price}' desc
I need to to order by "price" desc.
The result must be
First record of result is second json
"availability": [
{
"qty": 25,
"price": 11599,
"is_available": true
},
{
"qty": 72,
"price": 13599,
},
"is_available": true
]
...
"availability": [
{
"qty": 25,
"price": 1599,
"is_available": true
},
{
"qty": 72,
"price": 3599,
},
"is_available": true
]
Is it possible?
解决方案
这可以这样做:
select id,
jsonb_set(data, '{availability}',
(select jsonb_agg(item order by (item ->> 'price')::numeric)
from jsonb_array_elements(data -> 'availability') as x(item))
) as data
from product
where ...
推荐阅读
- tensorflow - 在数据集中使用具有多个输出的张量流时间序列预测时的损失计算
- google-cloud-platform - 为什么在谷歌云盔甲中禁用了某些规则操作?
- ffmpeg - 从 10 位视频中获取 10 位 RGB 值
- echarts - 如何使用echarts图强制更新单节点?不重新加载整个 echarts
- arrays - Google 电子表格:比较来自不同标签的文本
- java - 非静态变量 this 不能从静态上下文中引用 Dormitory dormitory = new Dormitory();
- python - 雪花查询中的编程错误
- python - YOLO:如何标注小物件?
- python - 如何在绘图中记录转换我的 y 轴?scale('log') 在熊猫中不起作用
- android - 迁移到 Flutter 2 后,由于 firebase_core 插件导致 Flutter 应用发布构建失败