【问题标题】:Json conversion in SQL Server - multiple rows in to single json arraySQL Server 中的 Json 转换 - 多行到单个 json 数组
【发布时间】:2021-07-04 14:15:25
【问题描述】:

数据集:

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 

【问题讨论】:

标签: json sql-server sorting sql-server-2016


【解决方案1】:

如果您将 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 

退货

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

【讨论】:

  • @vignesh 永远不明白为什么从未添加简单数组作为内置函数/功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
相关资源
最近更新 更多