在SQL中将行转换为列

时间:2012-12-01 20:09:37

标签: sql sql-server pivot

我怎么能这样做?

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以使用PIVOT表运算符将这些课程成绩的行转换为列,如下所示:

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

这会给你:

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);

Dynamic SQL Fiddle Demo