1

Assume we have couple of objects in database with attribute data where attribute data consists: {'gender' => {'male' => 40.0, 'female' => 30.0 => 'undefined' => 30.0}}.

I would like to find only these objects, which have the gender => male value the highest.

PostgreSQL 9.5

1
  • 1
    select * from your_table where 'male' = (select k from json_each_text(data->'gender') as j(k,v) order by v::numeric desc limit 1); Commented Nov 24, 2016 at 13:14

1 Answer 1

2

Assuming I understand your question correctly (example input/output would be useful):

WITH jsons(id, j) AS (
  VALUES
    (1, '{"gender": {"male": 40.0, "female": 30.0, "undefined": 30.0}}'::json),
    (2, '{"gender": {"male": 40.0, "female": 30.0, "undefined": 30.0}}'),
    (3, '{"gender": {"male": 0.0, "female": 30.0, "undefined": 30.0}}')
)
SELECT id, j
FROM jsons
WHERE (j->'gender'->>'male') :: float8 = (
  SELECT MAX((j->'gender'->>'male') :: float8)
  FROM jsons
)
;
┌────┬───────────────────────────────────────────────────────────────┐
│ id │                               j                               │
├────┼───────────────────────────────────────────────────────────────┤
│  1 │ {"gender": {"male": 40.0, "female": 30.0, "undefined": 30.0}} │
│  2 │ {"gender": {"male": 40.0, "female": 30.0, "undefined": 30.0}} │
└────┴───────────────────────────────────────────────────────────────┘
(2 rows)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.