过滤表列并查看另一列中的数据

时间:2013-02-27 07:18:37

标签: php mysql sql pivot

表'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..

2 个答案:

答案 0 :(得分:6)

  

我无法解释这个

让我为你解释一下。

您正在为每位学生寻找旋转 comments的{​​{1}}值。不幸的是,MySQL没有数据透视表运算符。

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

CASE

SQL Fiddle Demo

这会给你:

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;

对于多个| STUDENT_NAME | ACCADEMICS | ACCOMODATION | ---------------------------------------------- | Anne Curtis | this acad.. | this is aco | | benedict grey | also acad.. | also accomo | 并且您不需要手动编写它们,您必须使用动态SQL动态执行此操作,如下所示:

concern

Updated SQL Fiddle Demo

答案 1 :(得分: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