在我的表中,有一個單元格包含一個 json- 物件陣列,該物件的一個??屬性是一個數字(我需要提取),其他屬性是字串。
[{"a":"bla","b":"5k", "c":"foo"}, {"a":"bla","b":"9k", "c":"baz"}, {"a":"bla","b":"15k", "c":"foo"}]
^ 單個 json 示例。
select
jsonb_array_elements("jsons") ->> 'a' as a,
jsonb_array_elements("jsons") ->> 'c' as c,
regexp_replace(jsonb_array_elements("jsons")->> 'b', '\D','','g')::numeric as num
from x.y
where "some filter here"
and "condition 1"
and "condition 2"
and "condition 3"
這個查詢給了我 30 個結果,
問題是,我找不到對數字求和的方法。即使是沒有條件的簡單總和也會回傳錯誤。
我是 sql 的新手,并不真正了解它的深度,所以我可能在這里遺漏了一些東西。
我想做的是這樣的事情
select
sum(
if(jsonb_array_elements("jsons") ->> 'a' = 'bla' and jsonb_array_elements("jsons") ->> 'c' = 'foo'
then(regexp_replace(jsonb_array_elements("jsons")->> 'b', '\D','','g')::numeric)
else(0)
)) as sum
from x.y
where "some filter here"
and "condition 1"
and "condition 2"
and "condition 3"
我希望在這種情況下,如果所有 jsons 與上面的示例相同,我將得到 600 (30 *(5 15)) 的結果
uj5u.com熱心網友回復:
您可以使用標量子查詢:
select t.*,
(select sum(regexp_replace(item ->> 'b', '\D', '')::numeric)
from jsonb_array_elements(t.jsons) as x(item)
where x.item ->> 'a' = 'bla'
and x.item ->> 'c' = 'foo') as b_sum
from the_table t
;
uj5u.com熱心網友回復:
您可以使用以下查詢
select
sum(regexp_replace(e.value ->> 'b', '\D', '')::numeric)
filter (where e.value ->> 'a' = 'bla' and e.value ->> 'c' = 'foo')
from
test t cross join jsonb_array_elements(t.jsons) e;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340189.html
標籤:json PostgreSQL 和
上一篇:為tsvector列構建統計資訊
下一篇:為什么這個SQL有效?[復制]
