I have 2 tables in my PostgreSQL database.
Table 1 has the 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
:
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
[
{
"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.
First, You need to convert the string to an array then join it with Allowed_Trans_Modes . After that, you can use jsonb_agg
to create array of 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.