在 Postgres 中通過 json 數組(存儲為 jsonb)中的鍵對錶進行排序 (Order a table by a key in an array of json (stored as jsonb) in Postgres)


問題描述

在 Postgres 中通過 json 數組(存儲為 jsonb)中的鍵對錶進行排序 (Order a table by a key in an array of json (stored as jsonb) in Postgres)

我有一個 postgres,它有一個 jsonb 列,它是一個 jsons 數組。

id  array_json
123 [{"end_time": 22, "start_time": 21}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
126 [{"end_time": 22, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]

我想在“start_time”之前訂購這些。一行有一個 json 數組。在這種情況下,排序必須考慮整個數組中最早的開始時間。如果兩個數組具有相同的開始時間,那麼哪個先出現並不重要。最終結果應該是:

id  array_json
126 [{"end_time": 22, "start_time": 0}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
123 [{"end_time": 22, "start_time": 21}]

我已經創建了 a這張桌子的小提琴。這應該怎麼做?


參考解法

方法 1:

This will work I think:

select id, array_json from the_table,
lateral (select min((d‑>>'start_time')::int) x from jsonb_array_elements(array_json) d) t(x)
order by x

Best regards, Bjarni

方法 2:

This query can be used:

select id, min(start_time) min_start_time, array_json 
from (
   select 
       id, 
       array_json,
       ‑‑ we must convert start_time to integer for right sort order
       (jsonb_array_elements(array_json)‑>>'start_time')::int4 as start_time
    from the_table
) tmp 
group by id, array_json
order by min_start_time;

(by user248884Bjarni RagnarssonSlava Rozhnev)

參考文件

  1. Order a table by a key in an array of json (stored as jsonb) in Postgres (CC BY‑SA 2.5/3.0/4.0)

#sql-order-by #jsonb #postgresql






相關問題

如果提到,按特定值自定義 SQL 記錄集順序 (Customize SQL recordset order by specific value (s) if mentioned)

SQL Server 中的 OrderBy 將正值放在負值之前 (OrderBy in SQL Server to put positive values before negative values)

Đếm từ hai bảng và sắp xếp nó theo số lượng SQL tồn tại (Count from two tables and sort it out by the number of exist SQL)

按組中的最大值排序 (Order by the max value in the group)

.net中的SQLite中不區分大小寫的順序 (case insensitive order by in SQLite in .net)

MySQL:對 GROUP_CONCAT 值進行排序 (MySQL: Sort GROUP_CONCAT values)

為 MySQL 選擇查詢自定義 order by (Customize order by for MySQL select query)

如何從 MySQL 表中檢索 10 個最新的 DISTINCT IP? (How to retrieve 10 latest DISTINCT IP's from a MySQL table?)

按存儲在文本列中的日期排序表 (Order table by date stored in text column)

如何在 JavaScript 中對對象集合進行自然排序? (How to natural-sort a collection of objects in JavaScript?)

在 Postgres 中通過 json 數組(存儲為 jsonb)中的鍵對錶進行排序 (Order a table by a key in an array of json (stored as jsonb) in Postgres)

添加 row_number() 時 Oracle 值發生變化 (Oracle values change when row_number() added)







留言討論