0

I have the following structure and query:

SELECT jsonb_path_query_array(jsonb '{"subscores": {"score_a": 2, "score_b": 3, "score_c": 4}}','$.subscores.* ? (@>2)');

which returns: [3,4] or

SELECT jsonb_path_query(jsonb '{"subscores": {"score_a": 2, "score_b": 3, "score_c": 4}}','$.subscores.* ? (@>2)');

which returns (as rows):

3
4

Is there a way to structure my query to get the object subset as a single row, single field value? i.e.:

{"score_b": 3, "score_c": 4}

given a dynamic set of scores, ie. some rows will have score_d, ..., etc

asked Sep 29, 2021 at 6:52

1 Answer 1

0

I think you need to unnest all elements and the aggregate them back:

SELECT jsonb_object_agg(key, value) 
from (
 select *
 from jsonb_each(jsonb '{"subscores": {"score_a": 2, "score_b": 3, "score_c": 4}}' -> 'subscores')
) as p
where (p.value)::int > 2
answered Sep 29, 2021 at 7:42
1
  • Thanks, that definitely works but will not perform well at scale, so will be curious to see if there's any better suggestion in the next few days otherwise will accept your answer. I'd move the WHERE clause to the subquery though to filter sooner. Commented Sep 29, 2021 at 8:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.