1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| 要求:查询出2门及2门以上不及格者的平均成绩 demo sql如下: -------------------------------------------------------------------------- CREATE TABLE `student2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `subject` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `score` double(255,0) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `student2` VALUES ('1', '张三', '数学', '90'); INSERT INTO `student2` VALUES ('2', '张三', '语文', '50'); INSERT INTO `student2` VALUES ('3', '张三', '地理', '40'); INSERT INTO `student2` VALUES ('4', '李四', '语文', '55'); INSERT INTO `student2` VALUES ('5', '李四', '政治', '45'); INSERT INTO `student2` VALUES ('6', '王五', '政治', '30'); INSERT INTO `student2` VALUES ('7', '马六', '地理', '80'); INSERT INTO `student2` VALUES ('8', '马六', '英语', '90');
+----+------+---------+-------+--------+ | id | name | subject | score | score2 | +----+------+---------+-------+--------+ | 1 | 张三 | 数学 | 90 | 10 | | 2 | 张三 | 语文 | 50 | 10 | | 3 | 张三 | 地理 | 40 | 10 | | 4 | 李四 | 语文 | 55 | 10 | | 5 | 李四 | 政治 | 45 | 10 | | 6 | 王五 | 政治 | 30 | 10 | | 7 | 马六 | 地理 | 80 | 10 | | 8 | 马六 | 英语 | 90 | 10 | +----+------+---------+-------+--------+ --------------------------------------------------------------------------
select name,subject,score,score<60 from student2 select name,sum(score<60) as gk ,avg(score) as pj from student2 group by name select name,sum(score<60) as gk ,avg(score) as pj from student2 group by name HAVING gk>=2 结果: +--------+------+---------+ | name | gk | pj | +--------+------+---------+ | 张三 | 2 | 60.0000 | | 李四 | 2 | 50.0000 | +--------+------+---------+ +++++++++++++ having 是对表的结果进行查询筛选 ++++++++ select * from student2 where id>1 select * from student2 having id>1 select * from student2 where id>1 having id<5
|