SQL Query fields as columns

前端 未结 2 1693
囚心锁ツ
囚心锁ツ 2020-12-21 03:56

I dont really know how to put this but please kindly check the details below.

Student

|Student_ID|Student_Name|
|1         |Ryan             


        
相关标签:
2条回答
  • 2020-12-21 04:20

    While @John's answer will work if you have a known number of subjects, if you have an unknown number of subjects then you can use prepared statements to generate this dynamically. Here is a good article:

    Dynamic pivot tables (transform rows to columns)

    Your code would look like this:

    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;
    

    See SQL Fiddle With Demo

    0 讨论(0)
  • 2020-12-21 04:26

    Try,

    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

    0 讨论(0)
提交回复
热议问题