请问我该怎么做?
问问题
16298 次
1 回答
4
您可以使用PIVOT
table 运算符将这些课程成绩的行转换为列,如下所示:
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 小提琴演示
这会给你:
COURSE GRADE 1 GRADE 2 GRADE 3 GRADE 4
A 15 17 (null) (null)
B 12 (null) (null) (null)
C 10 18 0 9
请注意:我使用排名功能ROW_NUMBER()
将PARTITION BY Course
它们分为四个等级。这样您就可以将它们分为这四个组。
如果你需要这个动态,以防有未知数量的等级。在这种情况下,您可以使用动态 SQL 来动态生成成绩列表,如下所示:
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);
动态 SQL 小提琴演示
于 2012-12-01T20:35:55.073 回答