【问题标题】:Format JSON as nested arrays based on id in SQL根据 SQL 中的 id 将 JSON 格式化为嵌套数组
【发布时间】:2020-09-09 10:28:17
【问题描述】:

我在 SQLS 服务器中有一个存储过程,它以以下 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 没有元组,只有数组和对象。您发布的是带有对象的嵌套数组
  • @PanagiotisKanavos 将编辑问题
  • 你能发布测试数据吗?谢谢。
  • @Zhorov 我现在已经添加了示例数据
  • @Sindu_ 太棒了。您的 SQL Server 版本是多少?一种可能的方法是基于FOR JSON AUTO 和基本字符串聚合。另请注意,您的预期输出不是有效的 JSON。

标签: sql arrays json sql-server select


【解决方案1】:

生成预期 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"
      }
    ]
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2019-10-31
    • 2020-10-02
    • 2019-04-10
    相关资源
    最近更新 更多