Search code examples
sqlpostgresqlaggregate-functionspsqljsonb

How to sum a value in a JSONB array in Postgresql?


Given the following data in the jsonb column p06 in the table ryzom_characters:

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

I am attempting to sum the value of progress. I have attempted the following:

    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;

Which correctly lists the values:

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

But now I would like to sum these values, which could be null.

How do I correctly sum an object field within an array?

Here is the table structure:

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

Solution

  • Use the function jsonb_array_elements() in a lateral join in the from clause:

    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;
    

    You can use left join instead of cross join to protect the query against inconsistent data:

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