Добро пожаловать в форум, Guest  >>   Войти | Регистрация | Поиск | Правила | В избранное | Подписаться
Все форумы / Microsoft SQL Server Новый топик    Ответить
 Как получить json вида?  [new]
minya13_85
Member

Откуда: Москва
Сообщений: 595
Microsoft SQL Server 2017 (RTM-CU8) (KB4338363) - 14.0.3029.16 (X64)   Jun 13 2018 13:35:56   Copyright (C) 2017 Microsoft Corporation  Developer Edition (64-bit) on Windows Server 2016 Datacenter 10.0 <X64> (Build 14393: ) (Hypervisor) 


Есть таблица вида:
DECLARE @T TABLE ([Name] VARCHAR(50),born date,passport VARCHAR(50),validUntil DATE,flight VARCHAR(50),datef DATE,class VARCHAR(5),id INT,escort int)
INSERT INTO @T 
SELECT 'Ivanov Maksim','1990-08-13','77123456','2025-08-13','S7 1313','2018-10-03','Э',1,'' 
UNION ALL 
SELECT 'Ivanov Sergey','2018-01-22','77123457','2025-01-13','S7 1313','2018-10-03','Э',2,1

SELECT * FROM @T


Нужно получить JSON вида

{"flights":[{
"date": "2018-10-03",
"flight": "S7 1313", 
"allotment": { 
				"code": "Э"
			  }
}],
"tourists":[{
"id": 1,
"name": "Ivanov Maksim",
"born": "1990-08-13",
"document": { 
			"number": "77123456",
			 "validUntil": "2025-08-13"
			 }
},
{"id": 2,
"name": "Ivanov Sergey",
"born": "2018-01-22",
"document": { 
			"number": "77123457",
			 "validUntil": "2025-01-13"
			 },
"escortedBy": 1 
}]
}


Написал запрос вида:
SELECT distinct datef AS [date],flight AS [flight]
,class AS [allotment.code]
FROM @T AS t 
FOR JSON PATH,ROOT('flight')


А как вложенности использовать тут?
29 сен 18, 14:09    [21689861]     Ответить | Цитировать Сообщить модератору
 Re: Как получить json вида?  [new]
felix_ff
Member

Откуда: Moscow
Сообщений: 1173
minya13_85,

with flights as (
   select 
          [datef] as [date],
          [flight] as [flight],
          [class] as [allotment.code]
   from @t
   group by [flight], [class], [datef]
),
tourists as (
   select
         [id] as [id],
         [name]  as [name],
         [born] as [born],
         [passport] as [document.number],
         [validuntil] as [document.validUntil],
         [flight],
         [class],
         [datef]
    from @t
)
select * from flights f cross apply (select t.[id], t.[name], t.[born], t.[document.number], t.[document.validUntil] from tourists t where t.[flight] = f.[flight] and t.[class] = f.[allotment.code] and t.[datef] = f.[date] for json path) x(tourists)
for json path, root('flights')
29 сен 18, 16:44    [21689906]     Ответить | Цитировать Сообщить модератору
Все форумы / Microsoft SQL Server Ответить