将嵌套JSON作为输出的SQL脚本
考虑到我有以下数据将嵌套JSON作为输出的SQL脚本,sql,sql-server,Sql,Sql Server,考虑到我有以下数据 create table #Temp(PropertyID nvarchar(255),BuildingID nvarchar(255),UnitID nvarchar(255),TenantName nvarchar(255),FieldName nvarchar(255),CurrentValue nvarchar(255),PreviousValue nvarchar(255)) insert into #Temp Values ('p1','B1','5','Spe
create table #Temp(PropertyID nvarchar(255),BuildingID nvarchar(255),UnitID nvarchar(255),TenantName nvarchar(255),FieldName nvarchar(255),CurrentValue nvarchar(255),PreviousValue nvarchar(255))
insert into #Temp Values
('p1','B1','5','Spencer','Lease_EndDate','01/01/2021','03/01/2021'),
('p1','B1','5','Spencer','MonthlyBaseRent','3232','3000'),
('p1','B1','5','BCR','MonthlyBaseRent','1000','1100'),
('p1','B1','6','EA','MonthlyBaseRent','5000','5100'),
('p1','B2','5','VR','MonthlyBaseRent','3232','3000'),*
我需要以下嵌套JSON格式的输出,但我得到的是类似[{},{},{}]的平面JSON
[
{
"PropertyID": "p1",
"Building": [
{
"BuildingID": "B1",
"Unit": [
{
"UnitID": "5",
"Tenant": [
{
"TenantName": "Spencer",
"Lease_EndDate": {
"CurrentValue": "01/01/2021",
"PreviousValue": "03/01/2021"
},
"MonthlyBaseRent": {
"CurrentValue": "3232",
"PreviousValue": "3000"
}
},
{
"TenantName": "BCR",
"MonthlyBaseRent": {
"CurrentValue": "1000",
"PreviousValue": "1100"
}
}
]
},
{
"UnitID": "6",
"Tenant": [
{
"TenantName": "EA",
"MonthlyBaseRent": {
"CurrentValue": "5000",
"PreviousValue": "5100"
}
}
]
}
]
},
{
"BuildingID": "B2",
"Unit": [
{
"UnitID": "5",
"Tenant": [
{
"TenantName": "VR",
"MonthlyBaseRent": {
"CurrentValue": "3232",
"PreviousValue": "3000"
}
}
]
}
]
}
]
}
]
这是一个嵌套JSON的示例,有两个级别。使用此模板可以根据需要构建尽可能多的级别
select PropertyID ,BuildingID,
(select UnitID ,
(select t1.TenantName, t1.FieldName, t1.CurrentValue,t1.PreviousValue
from #Temp t1
where t1.PropertyID = t2.PropertyID and t1.BuildingID = t2.BuildingID and t1.UnitID = t2.UnitID
for json path) Tenant
from #Temp t2
where t2.PropertyID = t3.PropertyID and t2.BuildingID = t3.BuildingID
group by UnitID, PropertyID ,BuildingID
for json path) Unit
from #Temp t3
group by PropertyID ,BuildingID
for json path
假设我像下面那样插入空值,上面的脚本跳过这些值。('p1','B1',null,null,null,'TotalRent','5000','5100'),('p1',null,null,null,'BuildingID','B3',null)它应该是,[{“PropertyID”:“p1”,“Building”:[{“Building_Id”:“B1”,“TotalRent”:{“CurrentValue”:“5000”,“PreviousValue”:“5000”},{“Building_Id”:{“CurrentValue”:“B3”,“PreviousValue”:null}}]@pts,使用