如何使用 [{}、{}、{}] 格式的数据值

How to work with data values formatted [{}, {}, {}]

如果这是一个简单的问题,我深表歉意 - 我在尝试 Google 寻求帮助时甚至在格式化问题时遇到了一些问题!

在我正在使用的其中一张表中,数据值如下所示:

Invoice ID Status Product List
1234 Processed [{"product_id":463153},{"product_id":463165},{"product_id":463177},{"pid":463218}]

我想统计每个订单购买了多少产品。计算“产品列表”列下的值的正确语法和方法是什么?我知道 count() 是错误的,我可能需要从字符串值中提取数据。

select invoice_id, count(Product_list) 

from quote_table

where status = 'processed'

group by invoice_id

您可以使用名为 json_array_lengthJSON 函数并将此列转换为 JSON 数据类型(尽可能长),例如:


select invoice_id, json_array_length(Product_list::json)  as count

from quote_table

where status = 'processed'

group by invoice_id;


 invoice_id | count 
------------+-------
     1234   |     4
(1 row)


如果您需要计算 json 列的特定 属性,您可以使用下面的查询。

此查询通过使用 create type, json_populate_recordset and subquery 计算 json 数据中的 product_id 来解决问题。

drop type if exists count_product;

create type count_product as (product_id int);

select 
    t.invoice_id, 
    t.status,
    (
        select count(*) from json_populate_recordset(
            null::count_product, 
            t.Product_list
        ) 
        where product_id is not null    
    ) as count_produto_id
from (
    -- symbolic data to use in query
    select 
        1234 as invoice_id, 
        'processed' as status, 
        '[{"product_id":463153},{"product_id":463165},{"product_id":463177},{"pid":463218}]'::json as Product_list 
) as t