I have a JSON string as follows:
DECLARE @json nvarchar(max)
SET @json = '{"value": [
{
"AEDAT": "20211110"
},
{
"AEDAT": "20211110"
},
{
"AEDAT": "20211110"
},
{
"AEDAT": "20211112"
},
{
"AEDAT": "20211112"
},
{
"AEDAT": "20211112"
}
]}';
Now I want to read this JSON in SQL Server using OPENJSON()
and find the MAX value for each AEDAT
. For this, I am using the following query:
SELECT MAX(value)
FROM OPENJSON(@json, '$.value')
The above query is returning a row with key value pair as below:
{"AEDAT":"20211112"}
My objective is to get only 20211112
as integer.
How to achieve this?
If you want to get the max value as integer, you need to use OPENJSON()
with explicit schema (the WITH
clause with columns definitions). This schema depends on the structure of the parsed JSON (in your case it's a JSON array):
SELECT MAX(AEDAT) AS MaxAEDAT
FROM OPENJSON(@json, '$.value') WITH (
AEDAT int '$.AEDAT'
)
If the parsed values are dates, you may try a different statement:
SELECT MAX(TRY_CONVERT(date, AEDAT, 112)) AS MaxAEDAT
FROM OPENJSON(@json, '$.value') WITH (
AEDAT varchar(8) '$.AEDAT'
)