Let us say I have a json object {'key1':0.5,'key2':0.3,'key3':0.1}
in a particular column in a table called test. I want to return the key of the highest value. To get the highest value, in postgres, I can write this query:
select greatest(column1->'key1',column1->'key2',column1->'key3') from test
Now, it returns the greatest value. But the one I want is the key associated with the highest value. Is this possible in postgres json querying?
You need to extract all key/value pairs as rows. Once you have done that, it's a greatest-n-per-group problem - without the "group" though as you are looking at all rows.
select k,val
from (
select t.*, row_number() over (order by t.val::numeric desc) as rn
from jsonb_each_text('{"key1":0.5,"key2":0.3,"key3":0.1}'::jsonb) as t(k,val)
) t
where rn = 1;
Online example: http://rextester.com/OLBM23414
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.