SQL - Json 查询

SQL - Json query

我有类似于下面的表,其中有一对多映射

DECLARE @T1 TABLE(RootId int, [Name] varchar(50))
DECLARE @T2 TABLE(Id int,RootId int, Category varchar(50))

INSERT INTO @T1
VALUES(1,'Some Name 12121'),(2,'Some Name 343434')

INSERT INTO @T2
VALUES(100,1,'Category 3333'),
        (101,1,'Category 2222'),
        (102,1,'Category 4444'),
        (103,1,'Category 5555'),
        (104,2,'Category 1111'),
        (105,2,'Category 77777')

我希望编写查询,以便它生成 json 如下格式,其中它有子项和数组

    [
  {
    "item": {
      "rootId": 1,
      "name": "Some Name 12121",
      "sub": [
        {
          "id": 100,
          "category": "Category 3333"
        },
        {
          "id": 101,
          "category": "Category 2222"
        }
      ]
    }
  }
]

我试过下面但无法达到预期的输出

SELECT T1.RootId,T1.Name,T2.Id AS [Sub.Id],T2.Category as [Sub.Category]
FROM @T1 T1
    INNER JOIN @T2 T2 ON T1.RootId = T2.RootId
FOR JSON PATH, root('item')

有没有一种查询方法可以生成预期的 Json

您需要做的就是(简单地)正确地为您的 table 添加别名,然后使用 AUTO 而不是 PATH:

SELECT T1.RootId,T1.Name,sub.Id AS Id,sub.Category as Category
FROM @T1 T1
    INNER JOIN @T2 sub ON T1.RootId = sub.RootId
FOR JSON AUTO, ROOT('item');

输出(应用格式美化器后):

{
    "item": [
        {
            "RootId": 1,
            "Name": "Some Name 12121",
            "sub": [
                {
                    "Id": 100,
                    "Category": "Category 3333"
                },
                {
                    "Id": 101,
                    "Category": "Category 2222"
                },
                {
                    "Id": 102,
                    "Category": "Category 4444"
                },
                {
                    "Id": 103,
                    "Category": "Category 5555"
                }
            ]
        },
        {
            "RootId": 2,
            "Name": "Some Name 343434",
            "sub": [
                {
                    "Id": 104,
                    "Category": "Category 1111"
                },
                {
                    "Id": 105,
                    "Category": "Category 77777"
                }
            ]
        }
    ]
}