繁体   English   中英

根据 SQL 中的 id 将 JSON 格式化为嵌套数组

[英]Format JSON as nested arrays based on id in SQL

我在 SQLS erver 中有一个存储过程,它以以下 JSON 格式提供输出:

[
   {
  "accountid":"12312312",
  "Id":1,
  "name":"Ace Signs Ltd"
   },
   {
  "accountid":"213123123",
  "Id":2,
  "name":"Workshare Technology"
   },
  {
  "accountid":"12312312",
  "Id":1,
  "name":"Ace Signs Ltd"
  },
  {
  "accountid":"123123123",
  "Id":2,
  "name":"Workshare"
   }
]

但我希望它们根据 ID 分组到嵌套数组中,如下所示。 具有相同ID的那些是一个元组。

   {
   "match":[
      [
        {
        "accountid":"12312312",
        "Id":1,
        "name":"Ace Signs Ltd"
        },
        {
        "accountid":"12312312",
        "Id":1,
        "name":"Ace Signs Ltd"
        }
      ],
      [
        {
        "accountid":"12312312",
        "Id":2,
        "name":"Workshare Technology"
        },
        {
        "accountid":"213123123",
        "Id":2,
        "name":"Workshare"
        }
       ]
      ]
    }

生成JSON的存储过程部分如下:

SELECT *
FROM TestJsonFormat 
FOR JSON AUTO

样本数据:

CREATE TABLE TestJsonFormat (
    accountid varchar(255), 
    Id int,
    name varchar(255)
)

insert into TestJsonFormat values(12312312,1,'Ace Signs Ltd')
insert into TestJsonFormat values(213123123,2,'Workshare Technology')
insert into TestJsonFormat values(12312312,1,'Ace Signs Ltd')
insert into TestJsonFormat values(123123123,2,'Workshare')

生成预期 JSON 输出的一种可能方法是FOR JSON AUTO和基本字符串聚合的组合。 以下示例演示了这一点:

桌子:

CREATE TABLE TestJsonFormat (
    accountid varchar(255), 
    Id int,
    name varchar(255)
)
insert into TestJsonFormat values(12312312,1,'Ace Signs Ltd')
insert into TestJsonFormat values(213123123,2,'Workshare Technology')
insert into TestJsonFormat values(12312312,1,'Ace Signs Ltd')
insert into TestJsonFormat values(123123123,2,'Workshare')

陈述:

SELECT CONCAT('{"match": [', STRING_AGG(json, ','), ']}')
FROM (
   SELECT DiSTINCT t.id, j.json
   FROM TestJsonFormat t
   CROSS APPLY (
      SELECT accountId, id, name
      FROM TestJsonFormat 
      WHERE id = t.id
      FOR JSON AUTO
   ) j (json)
) cte

结果(格式化):

{
  "match": [
    [
      {
        "accountId":"12312312",
        "id":1,
        "name":"Ace Signs Ltd"
      },
      {
        "accountId":"12312312",
        "id":1,
        "name":"Ace Signs Ltd"
      }
    ],
    [
      {
        "accountId":"213123123",
        "id":2,
        "name":"Workshare Technology"
      },
      {
        "accountId":"123123123",
        "id":2,
        "name":"Workshare"
      }
    ]
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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