[英]Creating JSON Array in PostgreSQL by reading comma separated values
I have 2 tables in my PostgreSQL database.我的 PostgreSQL 数据库中有 2 个表。
Table 1 has the Product_Details
:表 1 有
Product_Details
:
Product_Name![]() |
Allowed_Transaction_Modes ![]() |
Category![]() |
---|---|---|
Salary_Account ![]() |
ATM,NEFT,UPI,GPay ![]() |
Premium![]() |
Savings_Account ![]() |
ATM,UPI, GPay ![]() |
Silver![]() |
The second table contains the description of these allowed transaction modes - Transaction_Models
:第二个表包含这些允许的事务模式的描述 -
Transaction_Models
:
Allowed_Trans_Modes ![]() |
Description![]() |
---|---|
NEFT ![]() |
National Electronic Funds Transfer![]() |
UPI ![]() |
Unified Payments Interface![]() |
GPay![]() |
Google Pay![]() |
ATM![]() |
Automated teller machine![]() |
I need to create the following JSON output by using a select query我需要使用选择查询创建以下 JSON 输出
[
{
"Product Name": "Salary Account",
"Allowed_Transaction_Modes": [
{
"code": "ATM",
"description": "Automated teller machine"
},
{
"code": "NEFT",
"description": "National Electronic Funds Transfer"
},
{
"code": "UPI",
"description": "Unified Payments Interface"
},
{
"code": "GPay",
"description": "Google Pay"
}
],
"Category": "Premium"
},
{
"Product Name": "Salary Account",
"Allowed_Transaction_Modes": [
{
"code": "ATM",
"description": "Automated teller machine"
},
{
"code": "UPI",
"description": "Unified Payments Interface"
},
{
"code": "GPay",
"description": "Google Pay"
}
],
"Category": "Silver"
}
]
Tried writing a few queries from Google but they do not work.尝试从 Google 编写一些查询,但它们不起作用。
First, You need to convert the string to an array then join it with Allowed_Trans_Modes .首先,您需要将字符串转换为数组,然后将其与Allowed_Trans_Modes连接。 After that, you can use
jsonb_agg
to create array of JSON之后,您可以使用
jsonb_agg
创建 JSON 数组
with data as (
select
pd."Product_Name",
pd."Category",
jsonb_agg(
jsonb_build_object(
'code',
tm."Allowed_Trans_Modes",
'description',
tm."Description"
)
) as agg
from
"Product_Details" pd,
"Transaction_Modesl" tm
where
tm."Allowed_Trans_Modes" = any(string_to_array(pd."Allowed_Transaction_Modes", ','))
group by
1, 2)
select
jsonb_agg(
jsonb_build_object(
'Product Name',
"Product_Name",
'Allowed_Transaction_Modes',
agg,
'Category',
"Category"
)
)
from
data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.