简体   繁体   中英

Nested JSON from SQL Server 2016

I have data like shown in the table below

X Y
1 A
1 B

and I'm trying to generate a JSON using FOR JSON PATH in SQL Server 2016 and getting JSON which looks like this:

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

But I'm expecting something which looks like combined one as shown below.

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

Can someone help me how to achieve this in SQL Server 2016? So far I've tried to get a nested JSON as a result of join.

;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

Try something like this:

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 will table distinct values from first column and then join it with main table by this column. FOR JSON AUTO will nest results and give you the structure that you need. Result is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM