簡體   English   中英

Postgres:Select 對象數組中值 >= x 以及沒有值大於 x 的所有行

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

我有一個看起來像這樣的表:

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}]

我想 output 所有predssentenceprob >= 0.5 但是,如果一個句子的probs不大於0.5 ,那么我也想將其包含在結果中。

例如,對於這個數據,結果應該是:

結果:


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

我這樣做適用於第一種情況(使用prob >= 0.5選擇preds )。 但是,我無法選擇probs不大於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

如果您使用的是 Postgres 12 或更高版本,則可以使用 JSON 路徑查詢:

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

對於那些沒有任何符合條件的項目的人,這將返回一個空數組[]


對於早期版本,我會使用:

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;

這將為沒有元素匹配的那些返回null

嘗試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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM