Du kan bruge <-koden>PIVOT tabeloperator til at transformere rækkerne af disse kursers karakterer til kolonne, som sådan:
SELECT
Course,
[1] AS "Grade 1",
[2] AS "Grade 2",
[3] AS "Grade 3",
[4] AS "Grade 4"
FROM
(
SELECT
Course,
Grade,
ROW_NUMBER() OVER(PARTITION BY Course
ORDER BY COURSE) rownum
FROM Grades
) t
PIVOT
(
MAX(Grade)
FOR rownum IN([1], [2], [3], [4])
) p;
SQL Fiddle Demo
Dette vil give dig:
COURSE GRADE 1 GRADE 2 GRADE 3 GRADE 4
A 15 17 (null) (null)
B 12 (null) (null) (null)
C 10 18 0 9
Bemærk at: Jeg brugte rangeringsfunktionen ROW_NUMBER()
med PARTITION BY Course
at opdele dem i fire klasser. Så du kan gruppere dem i disse fire grupper.
Hvis du har brug for dette dynamisk, hvis der var ukendt antal karakterer. Du kan bruge dynamisk SQL i dette tilfælde til at generere listen over karakterer dynamisk som sådan:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
SELECT @cols = STUFF((SELECT distinct ','
+ QUOTENAME('Grade '
+ CAST(ROW_NUMBER() OVER(PARTITION BY Course
ORDER BY Course) AS VARCHAR(10)))
FROM Grades
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
SELECT @query = 'SELECT Course, ' + @cols +
'FROM
(
SELECT
Course,
Grade,
''Grade '' + CAST(ROW_NUMBER()
OVER(PARTITION BY Course
ORDER BY COURSE) AS VARCHAR(10)) rownum
FROM Grades
) t
PIVOT
(
MAX(Grade)
FOR rownum IN(' + @cols + ')' +
') p';
execute(@query);