简体   繁体   English

通过读取逗号分隔值在 PostgreSQL 中创建 JSON 数组

[英]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 Allowed_Transaction_Modes Category类别
Salary_Account Salary_Account ATM,NEFT,UPI,GPay ATM、NEFT、UPI、GPay Premium优质的
Savings_Account Savings_Account ATM,UPI, GPay ATM、UPI、GPay Silver

The second table contains the description of these allowed transaction modes - Transaction_Models :第二个表包含这些允许的事务模式的描述 - Transaction_Models

Allowed_Trans_Modes Allowed_Trans_Modes Description描述
NEFT NEFT National Electronic Funds Transfer全国电子资金转账
UPI 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 数组

Demo 演示

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM