Get nest multiple section as JSON using Sql query

Binumon George 161 Reputation points
2023-01-17T13:04:18.4866667+00:00

I am giving my table Structure below

tblOrganization

OrganizationId

OrganizationName

OrganizatioEmail

tblLocation

LocationId

OrganizationId Here may contain multiple location aginist one Organization

LocationName

tblContact

ContactId

OrganizationId Here may contain multiple contact aginist one Organization

ContactName

tblSpecialities

SpecialityId

SpecialityName

tblOrganizationSpecialities

SpecialityId Mapping table Organization and Specialities. Here may contain multiple Specialities aginist one Organization

OrganizationId

Please help me write sql query to get below output

Expected Result

{
	"Data": [{
		"organizationId": 333,
		"organizationName": "Org3",
		"OrganizatioEmail": "Org1TIN3@org.com",
		"location": [
		  {"LocationName": "Location1"},
		  {"LocationName": "Location2"},
		  {"LocationName": "Location3"}
		],
		"contact": [
		  {"ContactName": "ContactName1"},
		  {"ContactName": "ContactName2"},
		  {"ContactName": "ContactName3"}
		],
		"specialities": [
		  {"specialityName": "Speciality1"},
		  {"specialityName": "Speciality2"},
		  {"specialityName": "Speciality3"}
		]

	}]
}
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,320 questions
0 comments No comments
{count} votes

Accepted answer
  1. Guoxiong 8,206 Reputation points
    2023-01-17T16:02:48.3666667+00:00

    Try the following code:

    SELECT 
    	OrganizationId, 
    	OrganizationName, 
    	OrganizatioEmail, 
    	(
    		SELECT LocationName 
    		FROM tblLocation 
    		WHERE OrganizationId = O.OrganizationId 
    		FOR JSON PATH
    	) AS Location,
    	(
    		SELECT ContactName 
    		FROM tblContact 
    		WHERE OrganizationId = O.OrganizationId 
    		FOR JSON PATH
    	) AS Contact,
    	(
    		SELECT S.SpecialityName 
    		FROM tblOrganizationSpecialities AS OS 
    		INNER JOIN tblSpecialities AS S ON OS.SpecialityId = S.SpecialityId 
    		WHERE OS.OrganizationId = O.OrganizationId
    		FOR JSON PATH
    	) AS Specialities
    FROM tblOrganization AS O
    FOR JSON PATH;
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 45,626 Reputation points
    2023-01-17T14:00:54.91+00:00
    0 comments No comments

  2. LiHongMSFT-4306 29,906 Reputation points
    2023-01-18T02:32:24.45+00:00

    Hi @Binumon George

    Have you check Guoxiong's answer? You could also use the ROOT option to specify a named root element, like this: FOR JSON PATH,ROOT('Data')

    Best regards,

    Cosmog Hong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.