Postgresql:按数字键值对 JSON 数组进行排序

And*_*Fox 2 postgresql json sql-order-by

我一直在阅读类似的问题,这些问题看起来有足够简单的解决方案,但在这里应用它们似乎对我不起作用。我在包含 x 和 y 坐标的 postgres 数据库表中有一个 json 列。在此列上执行简单的选择会返回以下示例:

[
{
 "x": "-1.6827080672804147",
 "y": "-0.011726425465745486"
},
{
 "x": "2.4016256261667235",
 "y": "0.016304356672382222"
},
{
 "x": "0.2278035109735127",
 "y": "0.0013854154958112177"
},
{
 "x": "1.2104642489702613",
 "y": "0.008129416140682903"
},
{
 "x": "-0.3281865438803838",
 "y": "-0.0024303442506510738"
},
{
 "x": "-0.2401461868455415",
 "y": "-0.0018261232803209514"
}, 
               .
               .
               .
               .
]
Run Code Online (Sandbox Code Playgroud)

我想按照 x 坐标升序返回这个对象。上面的结果集实际上是运行以下查询的结果:

  SELECT coordinates 
    FROM schema_name.table_name
   WHERE ....
     AND ....
ORDER BY coordinates ->> 'x' asc;
Run Code Online (Sandbox Code Playgroud)

我也尝试使用

ORDER BY cast(coordinates->>'x' as numeric)  ASC
Run Code Online (Sandbox Code Playgroud)

产生以下结果:

ERROR:  cannot cast type json to numeric
Run Code Online (Sandbox Code Playgroud)

我确定这是我错过的一些愚蠢的东西。任何指向正确方向的指针将不胜感激。

kli*_*lin 6

没有必要把事情搞得太复杂,你可以order byjson_agg():

create or replace function sort_my_array(json)
returns json language sql as $$
    select json_agg(value order by (value->>'x')::numeric)
    from json_array_elements($1)
$$
Run Code Online (Sandbox Code Playgroud)

Db小提琴。