如何获取JSONB数组索引
How to get JSONB array index
我确定对此有一个简单的答案,但我就是找不到。我需要获取 JSON 数组元素作为行,但它们的索引与后续处理有关。这是一个[非常简化]的例子:
id content
-- ------------------------------------------------------------------
80 {"id":"107-80", "Sections": [{"parts":5},{"parts":8},{"parts":4}]}
我需要得到:
id section section_content
-- ------- ---------------
80 0 {"parts":5}
80 1 {"parts":8}
80 2 {"parts":4}
我试过:
select
id,
row_number() over() - 1 as section,
jsonb_array_elements(content -> 'Sections') as section_content
from purchase
但是section
列计算不正确,如下图:
id section section_content
--- -------- ---------------
80 0 {"parts":5}
80 0 {"parts":8}
80 0 {"parts":4}
您可以使用with ordinality
select p.id, s.*
from purchase p
cross join jsonb_array_elements(p.content -> 'Sections') with ordinality as s(section_content, section)
您可以将其用作 CTE
CREATE TABLE purchase (
"id" INTEGER,
"content" JSONB
);
INSERT INTO purchase
("id", "content")
VALUES
('80', '{"id":"107-80", "Sections": [{"parts":5},{"parts":8},{"parts":4}]}');
WITH CTE AS (select
id,
jsonb_array_elements(content -> 'Sections') as section_content
from purchase)
SELECT
id, ROW_NUMBER () OVER (
PARTITION BY id) as section, section_content FROM CTE
id | section | section_content
-: | ------: | :--------------
80 | 1 | {"parts": 5}
80 | 2 | {"parts": 8}
80 | 3 | {"parts": 4}
db<>fiddle here
我确定对此有一个简单的答案,但我就是找不到。我需要获取 JSON 数组元素作为行,但它们的索引与后续处理有关。这是一个[非常简化]的例子:
id content
-- ------------------------------------------------------------------
80 {"id":"107-80", "Sections": [{"parts":5},{"parts":8},{"parts":4}]}
我需要得到:
id section section_content
-- ------- ---------------
80 0 {"parts":5}
80 1 {"parts":8}
80 2 {"parts":4}
我试过:
select
id,
row_number() over() - 1 as section,
jsonb_array_elements(content -> 'Sections') as section_content
from purchase
但是section
列计算不正确,如下图:
id section section_content
--- -------- ---------------
80 0 {"parts":5}
80 0 {"parts":8}
80 0 {"parts":4}
您可以使用with ordinality
select p.id, s.*
from purchase p
cross join jsonb_array_elements(p.content -> 'Sections') with ordinality as s(section_content, section)
您可以将其用作 CTE
CREATE TABLE purchase ( "id" INTEGER, "content" JSONB ); INSERT INTO purchase ("id", "content") VALUES ('80', '{"id":"107-80", "Sections": [{"parts":5},{"parts":8},{"parts":4}]}');
WITH CTE AS (select id, jsonb_array_elements(content -> 'Sections') as section_content from purchase) SELECT id, ROW_NUMBER () OVER ( PARTITION BY id) as section, section_content FROM CTE
id | section | section_content -: | ------: | :-------------- 80 | 1 | {"parts": 5} 80 | 2 | {"parts": 8} 80 | 3 | {"parts": 4}
db<>fiddle here