Nest Json Array合并

时间:2018-05-21 02:06:32

标签: sql-server tsql sql-server-2016 json-query

我的表中有一个列保存的json数据:

rxjs@^5.0.0

是否可以获得如下结果:

declare @json nvarchar(max)
set @json = N'
{
    "Companies": [
        {
            "CompanyId": "A",
            "Employee": null
        },
        {
            "CompanyId": "B",
            "Employee": [
                {
                    "EmployeePictureId": null,
                    "Name": "Employee1"
                },
                {
                    "EmployeePictureId": "PictureId2",
                    "Name": "Employee2"
                }
            ]
        },
        {
            "CompanyId": "C",
            "Employee": [
                {
                    "EmployeePictureId": null,
                    "Name": "Employee3"
                },
                {
                    "EmployeePictureId": null,
                    "Name": "Employee4"
                }
            ]
        }
    ]
}
'

使用{ "EmployeePictureIds": ["PictureId2"] } Json_QueryJson_Value ...

仅获取OPENJSON并跳过空(null)数据

顺便说一下,数组中元素的数量是不确定的。

1 个答案:

答案 0 :(得分:0)

在SQL Server 2017中,您可以使用以下查询:

select json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE( A.EmployeePictureId , 'json') 
                  + '"', char(44)))) as [EmployeePictureIds]
FROM OPENJSON(@json, '$.Companies')
WITH 
( 
  CompanyId  NVARCHAR(MAX),
  Employee  NVARCHAR(MAX)  as json  
) as B
cross apply openjson (B.Employee)  
with  
(  
    EmployeePictureId VARCHAR(50),  
    [Name] VARCHAR(50)
) as A     
where A.EmployeePictureId is not null
for json path , WITHOUT_ARRAY_WRAPPER

您提供的JSON的结果:

enter image description here

添加另一个非空EmployeePictureId的结果:

enter image description here