Для достижения вашей цели вам понадобится одна из моих любимых комбинаций:
А теперь решение:
WITH orderedCourse AS
(
SELECT GroupId,
CourseLabel,
ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY CourseDate) AS CourseNumber
FROM @myCourses
)
SELECT TOP (1) GroupId, [1], [2], [3], [4]
FROM
(
SELECT GroupId,
CourseLabel,
CourseNumber
FROM orderedCourse
) AS src
PIVOT
(
MIN(CourseLabel) -- default agregate
FOR CourseNumber IN ([1], [2], [3], [4] /*... if you have more courses by group*/)
) AS pvt
ORDER BY GroupId
Что дает результат:
1001 vsp,science,BBA vsp,Maths,Btech vsp,Maths,Btech NULL
Я использовал этот код для объявления таблицы:
INSERT INTO @myCourses
SELECT 1001, 'vsp,science,BBA', CAST('25-05-2020' AS date) UNION ALL
SELECT 1001, 'vsp,Maths,Btech', CAST('26-05-2020' AS date) UNION ALL
SELECT 1001, 'vsp,Maths,Btech', CAST('27-05-2020' AS date) UNION ALL
SELECT 1002, 'yd,science,BBA', CAST('24-05-2020' AS date) UNION ALL
SELECT 1002, 'blr,Maths,Btech', CAST('25-05-2020' AS date);
SELECT GroupId,
CourseLabel,
CourseDate,
ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY CourseDate) AS CourseNumber
FROM @myCourses;