简体   繁体   中英

Sorting Jsonb inner node in PostgreSQL

I have a details::Jsonb column in which data is stores as follows:

{"competitor_weight": {"weight": "", "data_source": "1"}}
{"competitor_weight": {"weight": "", "data_source": "1"}}
{"competitor_weight": {"weight": "5", "data_source": "1"}}
{"competitor_weight": {"weight": "25", "data_source": "0"}}
{"competitor_weight": {"weight": "20", "data_source": "1"}}
{"competitor_weight": {"weight": "20", "data_source": "1"}}
{"competitor_weight": {"weight": "15", "data_source": "1"}}
{"competitor_weight": {"weight": "15", "data_source": "1"}}

I want to sort it as per the 'weight' node to generate result:

  Weight
    25
    20
    20
    15
    15
    5

I have done like

select details -> 'competitor_weight' ->> 'weight' as weight
from sample_table
order by COALESCE(details -> 'competitor_weight' ->> 'weight', '0') DESC

But the result comes as:

Weight
 5
25
20
20
15
15

You need to cast it to a number, currently your sorting is done on the ASCII strings. For that you also need to deal with the empty strings by converting them to null. You can get rid of the coalesce if you use nulls last to put the null values to the end

select details -> 'competitor_weight' ->> 'weight' as weight
from sample_table
order by nullif(details -> 'competitor_weight' ->> 'weight','')::int DESC nulls last

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM