用一條SQL語句查出每門課都大於80分的學生的姓名,數據表結構如下: 建表SQL如下: 查詢每門課都大於80分的同學的姓名: 查詢平均分大於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);
查詢平均分大於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;