sql-选修课-平均成绩-选修多门课

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40836026/article/details/80787171

选修课表:

    DROP TABLE IF EXISTS `chosen_class`;
    CREATE TABLE `chosen_class` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `s_id` int(11) DEFAULT NULL,
              `c_id` int(11) DEFAULT NULL,
              `grade` int(11) DEFAULT NULL,
              PRIMARY KEY (`id`)

    ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

   选修课表数据:

    insert  into `chosen_class`(`id`,`s_id`,`c_id`,`grade`) values (1,4,1,80),(2,1,2,70),(3,2,3,60),(4,1,4,60),(5,1,5,80),(6,2,5,50),(7,2,1,40),(8,4,6,90),(9,1,1,30);

学生表:

    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
              `s_id` int(11) NOT NULL AUTO_INCREMENT,
              `s_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci DEFAULT NULL,
              PRIMARY KEY (`s_id`)

       )  ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

学生表数据:

    insert  into `student`(`s_id`,`s_name`) values (1,'王二强'),(2,'李泽朋'),(3,'杨文龙'),(4,'王芯柯'),(5,'高航'),(6,'张三');

---------------------------------

1) 没有选修课程编号为"C1"的学生姓名

select c.c_name  from  class c LEFT JOIN student s on c.s_id=s.id

select s.s_name from  student s LEFT JOIN  chosen_class cc on s.s_id = cc.c_id LEFT JOIN  t_class c on c.id= cc.c_id where c.classname!='C1'


2) 列出每门课程名称和平均成绩,并按照成绩排序

select c.c_name, avg(cc.grade)  from chosen_class cc LEFT JOIN class c on c.c_id=cc.c_id GROUP BY c.c_name  ORDER BY cc.grade asc 


3) 选了2门课以上的学生姓名


select s.s_name,count(cc.c_id) '课程个数' from chosen_class cc LEFT JOIN student s on s.s_id=cc.s_id GROUP BY cc.s_id having count(cc.c_id) >2

展开阅读全文

没有更多推荐了,返回首页