[英]Creating JSON Array in PostgreSQL by reading comma separated values
我的 PostgreSQL 数据库中有 2 个表。
表 1 有Product_Details
:
产品名称 | Allowed_Transaction_Modes | 类别 |
---|---|---|
Salary_Account | ATM、NEFT、UPI、GPay | 优质的 |
Savings_Account | ATM、UPI、GPay | 银 |
第二个表包含这些允许的事务模式的描述 - Transaction_Models
:
Allowed_Trans_Modes | 描述 |
---|---|
NEFT | 全国电子资金转账 |
UPI | 统一支付接口 |
支付宝 | 谷歌支付 |
自动柜员机 | 自动取款机 |
我需要使用选择查询创建以下 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"
}
]
尝试从 Google 编写一些查询,但它们不起作用。
首先,您需要将字符串转换为数组,然后将其与Allowed_Trans_Modes连接。 之后,您可以使用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.