在MySQL Query中将行转换为列

时间:2016-03-01 07:16:55

标签: mysql pivot

enter image description here

我从这个查询得到了上面的结果

   SELECT sa.Student_Id,
   CONCAT_WS(' ', es.Student_FName, es.Student_LName) AS Full_Name, 
   sa.Attendance_Date ,  
   sa.Attendance_Status 
   FROM student_attendance sa 
   INNER JOIN courses c 
     ON c.Course_Id = sa.Course_Id
   INNER JOIN campus ca 
     ON ca.Campus_Id = c.Campus_Id
   INNER JOIN students es 
     ON es.Student_Id =  sa.Student_Id
   WHERE sa.Course_Id = 1  
     ORDER BY sa.Attendance_Date DESC;  


但我想要这个结果

enter image description here

有人可以帮我这样做..

2 个答案:

答案 0 :(得分:0)

     select max(student|_id),full_name as student_FName ,
     case attendance_date when attendance_date ='03-02-2016' and attendance_status =0 
     and full_name ='Shehriar Khan'
     Then 'p' end as '3/1/2016',
     case attendance_status when attendance_date ='03-01-2016' 
     and attendance_status =0 and full_name ='Ahtesham Illahi'
     Then 'p' end as '3/2/2016'
     from table_name 
     group_by full_name,attendance_date,attendance_stauts  

答案 1 :(得分:0)

试试这个

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
     'MAX(IF(a.attendance_status = ''',
        attendance_status,
        ''', IF(a.attendance_status = "1","P","X"), NULL)) AS "',
        attendance_date,'"'
     )
   ) INTO @sql
FROM student_attendance;


SET @sql = CONCAT('SELECT a.Student_ID,a.student_name,', @sql, ' 
               FROM student_attendance a
               LEFT JOIN student_attendance AS b
                ON a.Student_ID=b.Student_ID GROUP BY a.Student_ID,b.Student_ID');

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

小提琴link