在 Postgres 資料庫中,我有一個 jsonb 列,其中包含以下專案的維度:
{
"370730255061723346": {"volume": 3, "weight": 3200, "length": 8},
"370730255061723353": {"volume": 2, "weight": 3600, "length": 9}
}
由于第一個鍵是一個 ID,我正在努力解決 jsonb 條目中其他資訊的尋址問題:
- 如何檢索 jsonb 的頂級條目數(此處:2)?
- 如何獲取鍵“長度”的值 - 并理想地總結它們?
uj5u.com熱心網友回復:
您可以使用 jsonb_each、jsonb_to_record、路徑提取運算子等 json 函式......即:
drop table if exists sample;
create temporary table sample
(
id serial,
dummy jsonb
);
insert into sample (dummy)
values ('{
"370730255061723346": {
"volume": 3,
"weight": 3200,
"length": 8
},
"370730255061723353": {
"volume": 2,
"weight": 3600,
"length": 9
}
}');
select *
from sample;
with myData as (
select id, d.length, d.volume, d.weight
from sample,
lateral (select * from jsonb_each(sample.dummy)) t,
lateral (select * from jsonb_to_record(t.value) as r(length int, volume int, weight int)) d
)
select sum(length)
from myData
where id = 1;
uj5u.com熱心網友回復:
使用將jsonb_each()頂級 JSON 物件擴展為一組鍵/值對的函式。
select key, value
from my_table
cross join jsonb_each(jsonb_column)
使用查詢作為所需聚合的來源。
select
count(*) as number_of_entries,
sum((value->'length')::int) as sum_of_lengths
from (
select key, value
from my_table
cross join jsonb_each(jsonb_column)
) s
或者,在 Postgres 12 中,您可以使用jsonb_path_query().
select
count(*) as number_of_entries,
sum((entry->'length')::int) as sum_of_lengths
from my_table
cross join jsonb_path_query(jsonb_column, '$.*') as entry
在db<>fiddle中測驗它。
閱讀檔案中的 json 函式。
uj5u.com熱心網友回復:
您需要將 JSON 轉換為一系列行,然后再聚合回來。為了避免對整個查詢進行分組,我會在派生表中進行聚合:
select t.other_column, d.*
from the_table t
cross join lateral (
select count(*) as num_elements,
sum((value ->> 'length')::int) as total_length
from jsonb_each(t.the_column) as e(id, value)
) as d
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436581.html
標籤:PostgreSQL jsonb
