假设我在名为{'key1':0.5,'key2':0.3,'key3':0.1}的表中的特定列中有一个json对象测试。我想返回最高值的key。为了获得postgres中的最高值,我可以编写以下查询:
select greatest(column1->'key1',column1->'key2',column1->'key3') from test现在,它返回最大的值。但我想要的是与最高值相关联的键。在postgres json查询中这是可能的吗?
发布于 2018-08-31 13:55:21
您需要将所有键/值对提取为行。一旦你这样做了,这就是一个greatest-n-per-group问题--没有"group“,尽管你正在查看所有行。
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;在线示例:http://rextester.com/OLBM23414
https://stackoverflow.com/questions/52106105
复制相似问题