-9

表'acad_concerns'

id  student_name    start_date  end_date    concern         comments

 1  Anne Curtis     2013-02-27  2013-02-28  Academics       this acad.. 
2   benedict grey   2013-02-27  2013-02-28  Academics       also acad..
3   Anne Curtis     2013-02-27  2013-02-28  Accomodation    this is aco
4   benedict grey   2013-02-27  2013-02-28  Accomodation    also accomo

我想这样查看:

    student_name    Accademics   Accomodation   


    Anne Curtis     this acad..  this is accom..
    benedict grey   also acad..  also accom..
4

2 回答 2

6

我无法解释这个

让我为你解释一下。

您正在寻找旋转每个学生的comments值。concern不幸的是,MySQL 没有数据透视表操作符。

但是,您可以使用CASE表达式来执行此操作。像这样:

SELECT 
  student_name,
  MAX(CASE WHEN concern = 'Academics'   THEN comments END) AS 'Accademics',
  MAX(CASE WHEN concern = 'Accomodation' THEN comments END) AS 'Accomodation'
FROM acad_concern    
GROUP BY student_name;

SQL 小提琴演示

这会给你:

|  STUDENT_NAME |  ACCADEMICS | ACCOMODATION |
----------------------------------------------
|   Anne Curtis | this acad.. |  this is aco |
| benedict grey | also acad.. |  also accomo |

对于多个concerns 并且您不需要手动编写它们,您必须使用动态 SQL 动态执行此操作,如下所示:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(concern = ''',
      concern, ''', comments, NULL)) AS ', '''', concern , '''')
  ) INTO @sql
FROM acad_concern;

SET @sql = CONCAT('SELECT student_name, ', @sql , '
    FROM acad_concern    
    GROUP BY student_name;');

prepare stmt 
FROM @sql;

execute stmt;

更新的 SQL Fiddle 演示

于 2013-02-27T07:21:37.957 回答
0
   SELECT distinct student_name
        (SELECT comments FROM acad_concern where student_name=student.student_name where concern='Accademics') 
    as Accademics,
        (SELECT comments FROM acad_concern where student_name=student.student_name where concern='Accomodation')
     as Accomodation  
        FROM acad_concern student
于 2013-02-27T07:22:21.443 回答