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
Could some one help me with this query
You need two levels of aggregation here, plus a final
FOR JSON.Unfortunately, SQL Server does not support
JSON_AGGorJSON_OBJECT_AGGwhich would have made this easier. You need to hack it with a combination ofSTRING_ESCAPEandSTRING_AGG, as well asJSON_QUERYto prevent double-escaping.db<>fiddle