用一條SQL語句查出每門課都大於80分的學生的姓名


用一條SQL語句查出每門課都大於80分的學生的姓名,數據表結構如下:

建表SQL如下:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
--
Table structure for grade
--
----------------------------
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade` (
`name`
varchar(255) NOT NULL,
`class`
varchar(255) NOT NULL,
`score`
tinyint(4) NOT NULL
) ENGINE
=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
--
Records of grade
--
----------------------------
INSERT INTO `grade` VALUES ('張三', '語文', '81');
INSERT INTO `grade` VALUES ('張三', '數學', '75');
INSERT INTO `grade` VALUES ('李四', '語文', '76');
INSERT INTO `grade` VALUES ('李四', '數學', '90');
INSERT INTO `grade` VALUES ('王五', '語文', '81');
INSERT INTO `grade` VALUES ('王五', '數學', '100');
INSERT INTO `grade` VALUES ('王五', '英語', '90');
SET FOREIGN_KEY_CHECKS=1;

 

查詢每門課都大於80分的同學的姓名:

SELECT DISTINCT name FROM grade WHERE name NOT IN(SELECT DISTINCT name FROM grade WHERE score <=80);

  更簡單的:

SELECT name FROM grade GROUP BY name HAVING MIN(score) > 80;

 

查詢平均分大於80的學生的姓名:

SELECT name FROM (SELECT COUNT(*) AS t,SUM(score) AS num,name FROM `grade` GROUP BY name) AS a WHERE a.num > 80*t;

 更簡單的:

select name, avg(score) as sc from grade g1 group by name having avg(score)>80 ;

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: