简体   繁体   中英

Postgres: Select all rows from array of objects where value >= x and also where no values are greater than x

I have a table that looks like this:

sentence  data  
good     [{"pred": "yes", 'prob': 0.6}, {"pred": "maybe", "prob": 0.4}, {"pred": "another", "prob": 0.7}]
bad      [{"pred": "unexpected", "prob": 0.4}, {"pred": "uncool", "prob": 0.3}]

I want to output all preds for a sentence that have prob >= 0.5 . However, if a sentence has no probs greater than 0.5 then I want to include that in the result as well.

For example, for this data, the result should be:

Result:


  sentence | preds 
-----------+-------
 good      | ['yes', 'another']
 bad       | null    
(2 rows)

I did this which works for the first case (picking preds with prob >= 0.5 ). However, I am not able to pick the sentences that have no probs greater than 0.5

SELECT sentence, jsonb_agg(data->'pred') AS preds
FROM table
CROSS JOIN jsonb_array_elements(table.data) AS data
WHERE data->>'prob' >= '0.5'
GROUP BY sentence

If you are using Postgres 12 or later, you can use a JSON path query:

select sentence, 
       jsonb_path_query_array(data, '$[*] ? (@.prob >= 0.5).pred') as preds
from the_table;

This would return an empty array [] for those that don't have any items matching the condition.


For earlier versions, I would use:

select t.sentence, 
       (select jsonb_agg(e.item -> 'pred')
        from jsonb_array_elements(t.data) as e(item)
        where (e.item ->> 'prob')::float >= 0.5) as preds
from the_table t;

This returns null for those where no element matches

Try left join lateral :

# with invars (sentence, data) as (
  values
  ('good', '[{"pred": "yes", "prob": 0.6}, {"pred": "maybe", "prob": 0.4}, {"pred": "another", "prob": 0.7}]'::jsonb),
  ('bad', '[{"pred": "unexpected", "prob": 0.4}, {"pred": "uncool", "prob": 0.3}]')
)
select sentence, jsonb_agg(d.data) as preds
  from invars
       left join lateral jsonb_array_elements(data) as d(data)
              on (d.data->>'prob')::numeric >= .5
 group by sentence;

┌──────────┬──────────────────────────────────────────────────────────────────┐
│ sentence │                            jsonb_agg                             │
├──────────┼──────────────────────────────────────────────────────────────────┤
│ bad      │ [null]                                                           │
│ good     │ [{"pred": "yes", "prob": 0.6}, {"pred": "another", "prob": 0.7}] │
└──────────┴──────────────────────────────────────────────────────────────────┘
(2 rows)

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