I have a column of a table with this kind of structure
{
"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":{...}
},
}
And what I’m looking on, it’s create a query that gets me all the stock of each warehouse like this:
"warehouse: {"Warehouse1": 100, "Warehouse32": 90, "Warehouse58": 43, ...}
Each row on the table has different keys, on some of them could be just one warehouse of multiple.
I’m still newbie on this kind of stuff with the jsonb columns, and what I have reasearched at the moment or get me close to the result is this: select warehouses->'Warehouse1'->'stock' from "general".inventory i ;
2
Answers
Reading the documentation, I found the answer with the function of jsonb_each, which gives me the key and the value from the column of warehouse.
You can use the
jsonb_each
function. This function expands the JSONB object into a set of key-value pairs, which you can then aggregate.