使用动态键从 jsonb 列中提取值

问题描述 投票:0回答:1

我有一列具有这种结构的表格

{
    "Warehouse1": {
        "stock": 100,
        "batches":{...}
    },
    "Warehouse32": {
        "stock": 90,
        "batches":{...}
    },
    "Warehouse58": {
        "stock": 43,
        "batches":{...}
    },
    "Warehouse99": {
        "stock": 55,
        "batches":{...}
    },
    "Warehouse101": {
        "stock": 12,
        "batches":{...}
    },
    "Warehouse151": {
        "stock": 99,
        "batches":{...}
    },
    "Warehouse152": {
        "stock": 44,
        "batches":{...}
    },
}

我正在查看的是,它创建一个查询,让我获得每个仓库的所有库存,如下所示:

"warehouse: {"Warehouse1": 100, "Warehouse32": 90, "Warehouse58": 43, ...}

桌子上的每一行都有不同的键,其中一些可能只是一个仓库或多个仓库。

我对 jsonb 列来说还是新手,我目前研究的或让我接近结果的是:

select warehouses->'Warehouse1'->'stock' from "general".inventory i ;

postgresql jsonb
1个回答
0
投票

您可以使用

jsonb_each
功能。此函数将 JSONB 对象扩展为一组键值对,然后您可以对其进行聚合。

SELECT jsonb_object_agg(key, value->'stock') AS warehouse_stock
FROM (
    SELECT key, value
    FROM inventory, jsonb_each(warehouses)
) AS expanded;
© www.soinside.com 2019 - 2024. All rights reserved.