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