2016-08-27 156 views
1

我有數據,如低於嵌套JSON 2016

enter image description here

所示的圖像中,我試圖在SQL Server 2016使用FOR JSON PATH並獲得JSON它看起來像這樣生成一個JSON:

[ 
{"X":1,"VAL":{"Y":"A"}} 
, 

{"X":1,"VAL":{"Y":"B"}} 
] 

但我期待看起來像一個組合如下所示的東西。

[ 
{"X":1,"VAL":{"Y":"A", "Y":"B"}} 
] 

有人可以幫助我如何在SQL Server 2016中實現這個嗎?到目前爲止,我試圖通過連接來獲取嵌套的JSON。

;WITH CTE (X,Y) AS 
(
    SELECT 1 , 'A' 
    UNION ALL 
    SELECT 1 , 'B' 
) 
SELECT 
    A.X, B.Y AS 'VAL.Y' 
FROM 
    CTE A 
INNER JOIN 
    CTE B ON A.X = B.X AND A.Y = B.Y 
FOR JSON PATH 

回答

0

嘗試是這樣的:

declare @t table (X int, Y varchar(1)); 

insert into @t(x,y) 
values (1,'A'), (1,'B'); 

with l1 as (select distinct x from @t) 
select l1.X, VAL.Y 
from l1 join @t as VAL on l1.x = VAL.x 
for json auto, without_array_wrapper 

CTE將從第一列的表不同的值,然後與主表通過此列加入。 FOR JSON AUTO將嵌套結果併爲您提供所需的結構。結果是:

{"X":1,"VAL":[{"Y":"A"},{"Y":"B"}]}