I'm trying to get the element with the newest date from various JSON arrays. But I can't get it to work. It returns all the elements from the arrays. I have tried several things with MAX, TOP(1), ORDER BY but with no luck. Can someone point me in the right direction.
This is what the query returns
And this is what I would like - the element where 'gyldigTil' is the newest date
This is the query I'm using
DECLARE @json NVARCHAR(MAX) =
N'{
"_index": "cvr-v-20220630",
"_type": "_doc",
"_id": "4006567262",
"_score": 1.0,
"_source": {
"Vrvirksomhed": {
"virksomhedsform": [
{
"virksomhedsformkode": 80,
"langBeskrivelse": "Anpartsselskab",
"kortBeskrivelse": "APS",
"sidstOpdateret": "2020-02-26T12:02:30+01:00",
"ansvarligDataleverandoer": "E&S",
"periode": {
"gyldigFra": "2016-06-10",
"gyldigTil": "2020-01-22"
}
},
{
"virksomhedsformkode": 10,
"langBeskrivelse": "Enkeltmandsvirksomhed",
"kortBeskrivelse": "ENK",
"sidstOpdateret": "2020-03-11T12:08:14+01:00",
"ansvarligDataleverandoer": "T&S",
"periode": {
"gyldigFra": "2020-01-23",
"gyldigTil": "2022-12-31"
}
}
],
"virksomhedsstatus": [
{
"sidstOpdateret": "2018-10-12T23:46:13+02:00",
"status": "NORMAL",
"periode": {
"gyldigFra": "2016-06-10",
"gyldigTil": "2018-10-08"
}
},
{
"sidstOpdateret": "2020-02-26T12:02:30+01:00",
"status": "UNDER KONKURS",
"periode": {
"gyldigFra": "2018-10-09",
"gyldigTil": "2020-01-21"
}
},
{
"sidstOpdateret": "2020-02-26T12:02:30+01:00",
"status": "OPLØST EFTER KONKURS",
"periode": {
"gyldigFra": "2020-01-22",
"gyldigTil": "2020-01-22"
}
}
],
"cvrNummer": 37803472,
"virksomhedMetadata": {
"nyesteHovedbranche": {
"sidstOpdateret": "2020-02-26T12:02:30+01:00",
"branchetekst": "Vejgodstransport",
"branchekode": "494100",
"periode": {
"gyldigFra": "2016-06-10",
"gyldigTil": "2020-01-22"
}
}
}
}
}
}';
SELECT cvrNummer,
branchetekst,
branchekode,
[Status],
VF.kortBeskrivelse,
VF.gyldigTil AS VF_gyldigTil,
VS.gyldigTil AS VS_gyldigTil
FROM OPENJSON(@JSON)
WITH (
cvrNummer NVARCHAR(50) '$."_source"."Vrvirksomhed"."cvrNummer"',
branchetekst NVARCHAR(255) '$."_source"."Vrvirksomhed"."virksomhedMetadata"."nyesteHovedbranche"."branchetekst"',
branchekode NVARCHAR(255) '$."_source"."Vrvirksomhed"."virksomhedMetadata"."nyesteHovedbranche"."branchekode"',
virksomhedsform NVARCHAR(MAX) '$."_source"."Vrvirksomhed"."virksomhedsform"' AS JSON,
virksomhedsstatus NVARCHAR(MAX) '$."_source"."Vrvirksomhed"."virksomhedsstatus"' AS JSON
)
CROSS APPLY OPENJSON(virksomhedsform)
WITH (
kortBeskrivelse NVARCHAR(50) '$.kortBeskrivelse',
gyldigTil date '$.periode.gyldigTil'
) VF
CROSS APPLY OPENJSON(virksomhedsstatus)
WITH (
[Status] NVARCHAR(50) '$.status',
gyldigTil date '$.periode.gyldigTil'
) VS