将数组中的值相加时出现类型转换问题 (array_agg)

Getting type cast issue when adding up the values from an array (array_agg)

我试图对 PostgreSQL 中数组的所有值求和,尝试了不同的方法但总是遇到问题 function sum(numeric[]) does not exist。即使我尝试过铸造,但仍然显示出同样的问题。我在这里遗漏了什么吗?

select array_to_json(array_agg(items)) FROM (SELECT SUM(p.total_price) FROM (SELECT 
ARRAY_AGG(cart_items.unit_price) FILTER (where cart_items.type = 2) AS total_price 
from cart inner join cart_items on cart_items.cart_id = cart.id where cart.id = 
40868884) AS p) AS items;

结果是:

                                          array_to_json                                          
-------------------------------------------------------------------------------------------------
[{"total_price":[1.867,1.867,1.867,1.867,1.867,1.21,1.867,1.867,1.56,1.867,1.867,1.867,44]}]

基本上,我想在从数据库中取出这些列 prices 的值后对其进行求和。

Fiddle

http://sqlfiddle.com/#!17/3fdd3/4

如果您想在 json "totalprice" 字段中汇总价格,那么您可以使用:

select t.*,
       (select sum(price)
        from (select json_array_elements_text(j.el->'total_price')::numeric as price
              from json_array_elements(t.x) j(el)
             ) j
       )
from (select '[{"total_price":[1.867,1.867,1.867,1.867,1.867,1.21,1.867,1.867,1.56,1.867,1.867,1.867,44]}]'::json as x) t