Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to query all system under SystemTypes in SQL database in a json format

I have a SQL table like below

GroupID CountryName CityName
1 India Nellore
1 India Chittoor
1 SriLanka Kadapa
2 China Beijing
2 China Vwk

i want to output as json format as below

[
  {
    "GroupId": 1,
    "Data": [
      {
        "Country" : "India",
        "City" : ["India" || "Nellore"] 
      },
      {
        "Country" : "SriLanka",
        "City" : ["Kadapa"] 
      }
    ]
  },
  {
    "GroupId": 2,
    "Data": [
      {
        "Country" : "China",
        "City" : ["Beijing" || "Vwk"] 
      }
    ]
  },
]

I tried to achieve this by different queries but didn’t get it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could some one help me with this query

>Solution :

You need two levels of aggregation here, plus a final FOR JSON.

Unfortunately, SQL Server does not support JSON_AGG or JSON_OBJECT_AGG which would have made this easier. You need to hack it with a combination of STRING_ESCAPE and STRING_AGG, as well as JSON_QUERY to prevent double-escaping.

WITH ByCountry AS (
    SELECT
      t.GroupId,
      t.CountryName,
      City = '[' + STRING_AGG('"' + STRING_ESCAPE(t.CityName, 'json') + '"', ',') + ']'
    FROM YourTable t
    GROUP BY
      t.GroupId,
      t.CountryName
)
SELECT
  c.GroupId,
  Data = JSON_QUERY('[' + STRING_AGG(j.json, ',') + ']')
FROM ByCountry c
CROSS APPLY (
  SELECT
    c.GroupId,
    c.CountryName,
    City = JSON_QUERY(c.City)
  FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
) j(json)
GROUP BY
  c.GroupId
FOR JSON PATH;

db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading