Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

sql server - Convert rows to columns in SQL

How can I do the following please?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the PIVOT table operator to do transform the rows of these course's grades into column, like so:

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

This will give you:

COURSE    GRADE 1   GRADE 2      GRADE 3     GRADE 4
  A         15        17          (null)     (null)
  B         12      (null)        (null)     (null)
  C         10        18            0           9

Note that: I used the ranking function ROW_NUMBER() with PARTITION BY Course to partition them into four grades. So that you could then group them into these four groups.

If you need to this dynamically, in case there was unknown number of grades. You can use dynamic SQL in this case to generate the list of grades dynamically like so:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...