SQL语句:把统计结果按照特定的列值转换成多列

来源:互联网 发布:网站源码模板带app 编辑:程序博客网 时间:2024/05/15 02:01

要求:查询每个老师所带毕业设计的汇总情况,毕业设计学生分本科、专科,院外、院内,要求得到的结果形式如下:

教师名 院内本科 园内专科 院外本科 院外专科 合计

 

相关的表有:学生表(包含学生层次)、教师表(教师名)、学生课题表(学生教师对应关系以及院内院外信息)。

 

SQL语句如下:

 

select

    teacher.teacher_name,ifnull(c1.c,0) v1,ifnull(c2.c,0) v2,ifnull(c3.c,0) v3,ifnull(c4.c,0) v4,
    (ifnull(c1.c,0)+ifnull(c2.c,0)+ifnull(c3.c,0)+ifnull(c4.c,0)) sum

 from teacher

 left outer join
 (

      select

           teacher_id,count(*) c

      from

           taskbook,student 
      where

            taskbook.taskbook_inner_task='院内' and degree_id>1 and student.student_id=taskbook.student_id
      group by

            teacher_id

  ) c1 using(teacher_id) 

 left outer join
 (

       select

            teacher_id,count(*) c

       from

            taskbook,student
        where

             taskbook.taskbook_inner_task='院内' and degree_id=1 and student.student_id=taskbook.student_id
        group by

             teacher_id

 ) c2 using(teacher_id)

left outer join
(

       select

             teacher_id,count(*) c

       from

             taskbook,student
        where

              taskbook.taskbook_inner_task='院外' and degree_id>1 and student.student_id=taskbook.student_id
        group by

               teacher_id

) c3 using(teacher_id)

left outer join
(

         select

                 teacher_id,count(*) c

          from

                 taskbook,student
          where

                  taskbook.taskbook_inner_task='院外' and degree_id=1 and student.student_id=taskbook.student_id
          group by teacher_id

) c4 using(teacher_id);

 

类似的问题有:在一个表中存储了学生的所有选修课程成绩,典型的列有:学号、课程号、成绩。需要得到的结果如下:

学号 课程1成绩 课程2成绩 课程3成绩

原创粉丝点击