[英]postgresql query a json col with array of objects
in my table there is one cell that contains a json- array of objects, one of the properties from the object is an number(that i need to extract), the others are strings.在我的表中,有一个单元格包含一个 json- 对象数组,该对象的一个属性是一个数字(我需要提取),其他属性是字符串。
[{"a":"bla","b":"5k", "c":"foo"}, {"a":"bla","b":"9k", "c":"baz"}, {"a":"bla","b":"15k", "c":"foo"}]
^ a single json example. ^ 单个 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"
this query gives me like 30 results,这个查询给了我 30 个结果,
the thing is, I cant find a way to sum the numbers.问题是,我找不到对数字求和的方法。 even a simple sum with no conditions returns an error.即使是没有条件的简单总和也会返回错误。
I'm new to sql and don't really know the depths of it, so im probably missing something over here.我是 sql 的新手,并不真正了解它的深度,所以我可能在这里遗漏了一些东西。
what I would like to do is something like this我想做的是这样的事情
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"
I expect that in this case if all the jsons are the same as in the example above I will get a result of 600 (30 *(5+15))我希望在这种情况下,如果所有 jsons 与上面的示例相同,我将得到 600 (30 *(5+15)) 的结果
You can use a scalar subquery:您可以使用标量子查询:
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
;
You can use the following query您可以使用以下查询
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.