SQL查询字段作为列

时间:2012-10-01 04:55:36

标签: mysql sql select pivot

我真的不知道该怎么做,但请查看下面的详细信息。

学生

|Student_ID|Student_Name|
|1         |Ryan        |
|2         |Camille     |
|3         |George      |

等级

|Student_ID|Subject |Grade
|1         |Math    |5 
|1         |English |3 
|1         |History |1
|2         |Math    |3 
|2         |English |4 
|2         |History |1 
|3         |Math    |5 
|3         |English |1 
|3         |History |2 

是否可以获得此结果?

Student_Name|Math|English|History
Ryan        |5   |3      |1
Camille     |3   |4      |1
George      |5   |1      |2

现在我通过首先使用列名称填充未绑定的数据网格,然后是学生姓名,然后添加每个学生姓名的详细信息,从而实现这一目标。这非常耗时,我想更好地优化查询。

提前致谢。

2 个答案:

答案 0 :(得分:11)

尝试,

SELECT  a.Student_name,
        MAX(CASE WHEN subject = 'MATH' THEN grade ELSE NULL END) MathGrade,
        MAX(CASE WHEN subject = 'ENGLISH' THEN grade ELSE NULL END) EnglishGrade,
        MAX(CASE WHEN subject = 'History' THEN grade ELSE NULL END) HistoryGrade
FROM    Student a
        LEFT JOIN Grade b
            ON a.Student_ID = b.Student_ID
GROUP BY a.Student_name

SQLFiddle Demo

答案 1 :(得分:3)

虽然如果你有一定数量的科目,@ John的答案会有效,但如果你有一定数量的科目,那么你可以使用预备语句来动态生成。这是一篇好文章:

Dynamic pivot tables (transform rows to columns)

您的代码如下所示:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(case when Subject = ''',
      Subject,
      ''' then Grade end) AS ',
      Subject
    )
  ) INTO @sql
FROM grade;

SET @sql = CONCAT('SELECT s.Student_name, ', @sql, ' 
                   FROM student s
                   LEFT JOIN grade AS g 
                    ON s.student_id = g.student_id
                   GROUP BY s.Student_name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

请参阅SQL Fiddle With Demo