转换行到SQL列(Convert rows to columns in SQL)

2019-08-03 10:13发布

我怎样才能做到以下吗?

Answer 1:

您可以使用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小提琴演示

这会给你:

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小提琴演示



文章来源: Convert rows to columns in SQL