I have an array like this and I want to extract its count into a single array. Can I do this in SQL Server?
[
{
"ItemName": "ITEM1",
"Details": [
{
"column1": "2021/Apr",
"Count": 10
},
{
"column1": "2021/May",
"count": 20
},
{
"column1": "2021/Jun",
"count": 30
}
]
},
{
"ItemName": "ITEM2",
"Details": [
{
"column1": "2021/Apr",
"count": 10
},
{
"column1": "2021/May",
"count": 25
},
{
"column1": "2021/Jun",
"count": 2
}
]
}
]
I want to convert this as following. How can I achieve this using SQL Server?
[
{
"ItemName": "ITEM1",
"Details": [10, 20, 30]
},
{
"ItemName": "ITEM2",
"Details": [10, 25, 2]
}
]
2
Answers
It ain’t pretty but:
I think in newer versions (like SQL Server 2022), you can create arrays in simpler ways (https://techcommunity.microsoft.com/t5/azure-sql-blog/announcing-json-enhancements-in-azure-sql-database-azure-sql/ba-p/3417071)
Try this
The idea is that you can
CROSS APPLY
moreOPENJSON
on columns parsed withAS JSON
To produce an array of scalars just concatenate
count
s with comma delimiter ordered bycolumn1
, wrap in square brackets and mark withJSON_QUERY
not to be treated as a string but as a full-bloodied JSON array by finalFOR JSON PATH
.