【发布时间】:2016-07-11 03:17:09
【问题描述】:
我正在使用 Microsoft SQL Server 2016。此版本支持 JSON。
我有一个 Person 表,其中包含以下数据:
| PersonId | FatherId | Name |
|---|---|---|
| 1 | NULL | 4th Grand Father |
| 2 | 1 | 3rd Grand Father |
| 3 | 2 | 2nd Grand Father |
| 4 | 3 | Grand Father |
| 5 | 4 | Father |
| 6 | 4 | Uncle |
| 7 | 6 | Cousin |
| 8 | 5 | Brother |
| 9 | 5 | Me |
我运行以下查询:
WITH Persons_CTE AS(
SELECT PersonId, FatherId, Name FROM Persons WHERE FatherId IS NULL
UNION ALL
SELECT P.PersonId, P.FatherId, P.Name FROM Persons P JOIN Persons_CTE PCTE
ON PCTE.PersonId = P.FatherId)
SELECT P.Name as Name, PCTE.Name as Children FROM Persons_CTE PCTE LEFT JOIN Persons P
ON P.PersonId = PCTE.FatherId
FOR JSON PATH
查询生成以下结果:
[
{
"Children":"4th Grand Father"
},
{
"Name":"4th Grand Father",
"Children":"3rd Grand Father"
},
{
"Name":"3rd Grand Father",
"Children":"2nd Grand Father"
},
{
"Name":"2nd Grand Father",
"Children":"Grand Father"
},
{
"Name":"Grand Father",
"Children":"Father"
},
{
"Name":"Grand Father",
"Children":"Uncle"
},
{
"Name":"Uncle",
"Children":"Cousin"
},
{
"Name":"Father",
"Children":"Brother"
},
{
"Name":"Father",
"Children":"Me"
}
]
我希望查询结果为以下分层格式。我该怎么做?
[
{
"Name":"4th Grand Father",
"Children":[
{
"Name":"3rd Grand Father",
"Children":[
{
"Name":"2nd Grand Father",
"Children":[
{
"Name":"Grand Father",
"Children":[
{
"Name":"Father",
"children":[
{
"Name":"Brother"
},
{
"Name":"Me"
}
]
},
{
"Name":"Uncle",
"children":[
{
"Name":"Cousin"
}
]
}
]
}
]
}
]
}
]
}
]
【问题讨论】:
标签: sql-server json