Json 在 SQL 服务器中的转换 - 多行到单个 json 数组

Json conversion in SQL Server - multiple rows in to single json array

数据集:

create table grievances(grivanceid int ,grivancedesc varchar(10)) 
create table grievanceType(grivanceid int ,grivanceType varchar(10))  

insert into grievances values (1,'abc') 
insert into grievanceType values (1,'type1')
insert into grievanceType values (1,'type2') 

期望的输出:

{
    "grivanceid": 1,
    "grivancedesc": "abc",
    "grivanceType": [ "type1", "type2"]
}

我的查询:未完全实现

select * 
from 
    (select 
         a.*, 
         stuff(list.grivanceType, 1, 1, '')  grivanceType 
     from 
         grievances a 
     cross apply 
         (select  
              ',' + grivanceType  
          from 
              grievanceType b  
          where  
              grivanceid = a.grivanceid  
          for xml path ('')
         ) list(grivanceType)) a 
for json path, without_array_wrapper 

如果将 XML 结果包装在 JSON_Query()

中会有所帮助

例子

Select *
      ,grivanceType = JSON_QUERY('['+stuff((Select concat(',"',grivanceType,'"' )  
                                              From  grievanceType 
                                              Where grivanceid =A.grivanceid  
                                              For XML Path ('')),1,1,'')+']'
                              )
 From  grievances A
 for json path, without_array_wrapper 

Returns

{
    "grivanceid": 1,
    "grivancedesc": "abc",
    "grivanceType": ["type1", "type2"]
}