Вы можете попробовать следующий подход, используя NTILE()
и FOR JSON PATH
:
Заявление:
;WITH cte AS (
SELECT
id AS [StudentID],
first_name as [FirstName],
last_name as [LastName],
email as [Email],
gender as [Gender],
NTILE(4) OVER (ORDER BY id) AS GroupID
FROM TestData
)
SELECT
DISTINCT t1.GroupID,
t2.Json
FROM cte t1
CROSS APPLY (
SELECT StudentID, FirstName, Email, Gender
FROM cte
WHERE GroupID = t1.GroupID
FOR JSON PATH
) t2 (Json)
Результат (используя данные теста):
GroupID Json
1 [{"StudentID":1,"FirstName":"Myrtie","Email":"mgunning0@bandcamp.com","Gender":"Female"}, ... ,{"StudentID":25,"FirstName":"Dante","Email":"dtoopeo@chronoengine.com","Gender":"Male"}]
2 [{"StudentID":26,"FirstName":"Hamilton","Email":"hginnanep@joomla.org","Gender":"Male"}, ... ,{"StudentID":50,"FirstName":"Enrika","Email":"ehayselden1d@weibo.com","Gender":"Female"}]
3 [{"StudentID":51,"FirstName":"Cirilo","Email":"cfrankcomb1e@blogspot.com","Gender":"Male"}, ... ,{"StudentID":75,"FirstName":"Zeke","Email":"zleal22@eepurl.com","Gender":"Male"}]
4 [{"StudentID":76,"FirstName":"Todd","Email":"tscandred23@who.int","Gender":"Male"}, ... ,{"StudentID":100,"FirstName":"Kristi","Email":"kpossek2r@wikispaces.com","Gender":"Female"}]