Potrzebny kod SQL to:
SELECT Course1_ID = MAX(CASE WHEN RowNum = 1 THEN ID END),
Course1_Name = MAX(CASE WHEN RowNum = 1 THEN Name END),
Course2_ID = MAX(CASE WHEN RowNum = 2 THEN ID END),
Course2_Name = MAX(CASE WHEN RowNum = 2 THEN Name END),
Course3_ID = MAX(CASE WHEN RowNum = 3 THEN ID END),
Course3_Name = MAX(CASE WHEN RowNum = 3 THEN Name END)
FROM ( SELECT ID,
Name,
RowNum = ROW_NUMBER() OVER(ORDER BY ID)
FROM Courses
) C;
Ale przy nieznanych treściach musisz wygenerować to dynamicznie:
DECLARE @SQL NVARCHAR(MAX) = 'SELECT ' +
STUFF(( SELECT ',Course' + RowNum + '_ID = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN ID END)
,Course' + RowNum + '_Name = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN Name END)'
FROM ( SELECT RowNum = CAST(ROW_NUMBER() OVER(ORDER BY ID) AS VARCHAR(10))
FROM Courses
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') +
' FROM ( SELECT ID,
Name,
RowNum = ROW_NUMBER() OVER(ORDER BY ID)
FROM Courses
) C;'
EXECUTE SP_EXECUTESQL @SQL;
Innym sposobem na osiągnięcie tego samego wyniku jest:
DECLARE @SQL NVARCHAR(MAX) = '';
SELECT @SQL = @SQL +
',Course' + RowNum + '_ID = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN ID END)
,Course' + RowNum + '_Name = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN Name END)'
FROM ( SELECT RowNum = CAST(ROW_NUMBER() OVER(ORDER BY ID) AS VARCHAR(10))
FROM Courses
) c;
SET @SQL = 'SELECT ' + STUFF(@SQL, 1, 1, '') + '
FROM ( SELECT ID,
Name,
RowNum = ROW_NUMBER() OVER(ORDER BY ID)
FROM Courses
) c;';
EXECUTE SP_EXECUTESQL @SQL;
Usuwa to kosztowne rozszerzenia XML do łączenia wierszy w kolumny
Jeśli kolejność kursów jest w ogóle istotna, możesz po prostu zmienić kolejność według klauzuli w ROW_NUMBER
funkcja.