生成数据的嵌套JSON

时间:2019-09-23 10:50:40

标签: sql json sql-server tsql sql-server-2017

我有下表和示例数据:

CatID        int
Catname      nvarchar(255)
product_ID   int
product_name nvarchar(255)

catid Catname      product_ID product_name
----- ------------ ---------- ------------
100   mycatname100 1          productname1
100   mycatname100 2          productname2
100   mycatname100 3          productname3
200   mycatname200 1          productname1
200   mycatname200 2          productname2
200   mycatname200 3          productname3
300   mycatname300 1          productname1
300   mycatname300 2          productname2
300   mycatname300 3          productname3

如何获取如下所示的JSON格式:

[
  {"catid":"100","catname":"mycatname100","products":[{"product_id":"1","product_name":"productName1"},{"product_id":"2","product_name":"productName2"},{"product_id":"3","product_name":"productName3"}]},
  {"catid":"200","catname":"mycatname200","products":[{"product_id":"1","product_name":"productName1"},{"product_id":"2","product_name":"productName2"},{"product_id":"3","product_name":"productName3"}]},
  {"catid":"300","catname":"mycatname300","products":[{"product_id":"1","product_name":"productName1"},{"product_id":"2","product_name":"productName2"},{"product_id":"3","product_name":"productName3"}]}
]

1 个答案:

答案 0 :(得分:2)

数据库设计可以使用一些规范化。话虽如此,您可以使用嵌套查询来创建嵌套JSON:

SELECT catid, catname, products = (
    SELECT product_id, product_name
    FROM t AS x
    WHERE x.catid = t.catid
    FOR JSON PATH
)
FROM t
GROUP BY catid, catname
FOR JSON AUTO

Demo on db<>fiddle