如何在Postgresql中对JSONB数组中的值求和?

wljmcqd8  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(201)

给定表ryzom_characters中的jsonb列p06中的以下数据:

-[ RECORD 1 ]------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    p06 | {
  "id": 675010,
  "cname": "Bob",
  "rpjobs": [
    {
      "progress": 25
    },
    {
      "progress": 13
    },
    {
      "progress": 30
    }
  ]
}

我正在计算progress的值。我尝试了以下操作:

SELECT 
c.cname AS cname,
jsonb_array_elements(c.p06->'rpjobs')::jsonb->'progress' AS value 
FROM ryzom_characters c
Where cid = 675010
ORDER BY value DESC 
LIMIT 50;

它正确列出了值:

cname  | value
--------+-------
 Savisi | 30
 Savisi | 25
 Savisi | 13
(3 rows)

但现在我想对这些值求和,它可能为空。
如何正确地对数组中的对象字段求和?
下面是表格结构:

Table "public.ryzom_characters"
    Column     |          Type          | Collation | Nullable | Default
---------------+------------------------+-----------+----------+---------
 cid           | bigint                 |           |          |
 cname         | character varying(255) |           | not null |
 p06           | jsonb                  |           |          |
 x01           | jsonb                  |           |          |
pcrecxhr

pcrecxhr1#

在from子句的横向连接中使用函数jsonb_array_elements()

select cname, sum(coalesce(value, '0')::int) as value
from (
    select 
        p06->>'cname' as cname, 
        value->>'progress' as value
    from ryzom_characters
    cross join jsonb_array_elements(p06->'rpjobs')
    where cid = 675010
    ) s
group by cname
order by value desc 
limit 50;

您可以使用左联接而不是交叉联接来保护查询不一致的数据:

left join jsonb_array_elements(p06->'rpjobs')
    on jsonb_typeof(p06->'rpjobs') = 'array'
    where p06->'rpjobs' <> 'null'
f87krz0w

f87krz0w2#

函数jsonb_array_elements()是一个返回集合的函数。因此,您应该将其用作行源(在FROM子句中)。在调用之后,您将得到一个表,其中每一行都包含一个数组元素。从那以后就相对容易了。

SELECT cname, 
       sum(coalesce(r.prog->>'progress'::int, 0)) AS value  
FROM ryzom_characters c,
     jsonb_array_elements(c.p06->'rpjobs') r (prog)
WHERE c.cid = 675010
GROUP BY cname 
ORDER BY value DESC 
LIMIT 50;

相关问题