如何编写查询来获取表列和 json 列数组元素作为 Postgres 中同一行中的列

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

我的表中有以下数据: enter image description here

我需要开发一个 SELECT 语句,其返回输出如下:

enter image description here

以下是创建表并生成上述数据的脚本:

CREATE TABLE employees.employee_data (
    emp_id              varchar(50)  PRIMARY KEY,
    associations        JSONB NOT NULL default '{}'::jsonb
);

INSERT INTO employees.employee_data
(emp_id, associations)
VALUES('1001', '{
                              "group_tags": [
                                {
                                  "orgId": "XYZCompany",
                                  "locationId": "Location01"
                                },
                                {
                                  "orgId": "XYZCompany",
                                  "locationId": "Location02"
                                }                               
                              ]
                            }'::jsonb);
                            

INSERT INTO employees.employee_data
(emp_id, associations)
VALUES('1002', '{
                              "group_tags": [
                                {
                                  "orgId": "ABCCompany",
                                  "locationId": "Location03"
                                },
                                {
                                  "orgId": "ABCCompany",
                                  "locationId": "Location04"
                                }                               
                              ]
                            }'::jsonb);

有人可以帮我解决这个问题吗?

postgresql
1个回答
0
投票

只需执行这样的查询

select emp_id , jsonb_array_elements(jsonb_path_query_array(associations , '$.group_tags[*].orgId')) orgId, 
jsonb_array_elements(jsonb_path_query_array(associations , '$.group_tags[*].locationId')) locationId
from employees.employee_data;

删除残留双引号的版本

select emp_id, 
regexp_replace(jsonb_array_elements(jsonb_path_query_array(associations , '$.group_tags[*].orgId'))::text,'^"|"$','','g') orgId, 
regexp_replace(jsonb_array_elements(jsonb_path_query_array(associations , '$.group_tags[*].locationId'))::text,'^"|"$','','g') locationId
from employees.employee_data;

拨弄测试

© www.soinside.com 2019 - 2024. All rights reserved.