簡體   English   中英

通過讀取逗號分隔值在 PostgreSQL 中創建 JSON 數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM