I have a table, like such:
| f1 [int] | f2 [int] | jo1 [json object] | ja [json array] |
ja is an array of multiple json objectd, structured like so:
[
{
"ja_f1": x [int],
"ja_f2": y [float]
},
...
]
For the sake of simplicity, let's assume the jo1 is also structured like the objects in ja
How do I flatten this to a single record? I'm trying to make it this:
| f1 | f2 | jo1_f1 | jo1_f2 | ja[0]ja_f1 | ja[0]ja_f2 | ... | ja[n]ja_f2 |
I've been using a CURSOR on OPENJSON with a CROSS APPLY to bring back the missing data, but it breaks it into segments and it's not really what I need. This is what it looks like:
DECLARE @CursorForJSON CURSOR;
DECLARE @JSON nvarchar(MAX); BEGIN SET @CursorForJSON = CURSOR FOR SELECT JSON_Query(ja) FROM mytable
OPEN @CursorForJSON
FETCH NEXT FROM @CursorForJSON
INTO @JSON
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT mt.f1 AS 'f1',
ja_f1,
ja_f2
FROM OPENJSON( @json )
WITH ( ja_f1 INT '$.ja_f1',
ja_f2 FLOAT '$.ja_f2')
CROSS APPLY mytable as mt
GROUP BY mt.f1, ja_f1, ja_f2
ORDER BY mt.f1 ASC;
FETCH NEXT FROM @CursorForJSON
INTO @JSON
END;
CLOSE @CursorForJSON ;
DEALLOCATE @CursorForJSON;
END;
Any guidance would be appreciated
EDIT: Fixed some errors in the pseudo code