Search code examples
jsonpostgresqlaggregate-functionsjsonb

how sum column group by jsonḃ postgres


Hi I have a colum jsnoḃ with this values

proyectos:
nomḃre:character_varying
fecha:datetime
campos: jsonḃ

the value of campos is =

{"lista": [{"valor": "10", "nombre": "sueldo"}, {"valor": "20", "nombre": "sueldo"}, {"valor": "25", "nombre": "sueldo"}]}

I I run this query ḃut not working

SELECT jsonb_array_elements(campos->'lista')->'nombre' as content,

       sum(((jsonb_array_elements(campos->'lista')->'valor'))::numeric) as cantidad
 FROM proyectos GROUP BY jsonb_array_elements(campos->'lista')->'nombre

The console show me the message:

ERROR:  cannot cast type jsonb to numeric
LINE 3: ...((jsonb_array_elements(campos->'lista')->'valor'))::numeric)...
                                                             ^
********** Error **********

ERROR: cannot cast type jsonb to numeric
SQL state: 42846
Character: 137

Any idea ?


Solution

  • Use the function jsonb_array_elements() in a lateral join to get array elements as value, the ->> operator to get json objects as text and cast the valor objects to numeric.

    select value->>'nombre' as nombre, sum((value->>'valor')::numeric)
    from proyectos
    cross join jsonb_array_elements(campos->'lista')
    group by 1
    
     nombre | sum 
    --------+-----
     sueldo |  55
    (1 row)