1. 程式人生 > >(1)mysql--查詢成績最高和最低的人

(1)mysql--查詢成績最高和最低的人

簡單描述:
成績表中有學生姓名、學生科目以及學生分數。查詢分數最高和分數最低的學生的以及學生的分數。注意的點如下:

1、group by,select 選擇的列,必須是group by 中的列,或者是函式形式。
2、利用MAX() 和MIN()sql函式。
3、建立的表結構如下。

-- ----------------------------
-- Table structure for grade
-- ----------------------------
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade` (
  `stu_name`
varchar(255) NOT NULL, `stu_subject` varchar(255) NOT NULL, `score` int(255) DEFAULT NULL, PRIMARY KEY (`stu_subject`,`stu_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ---------------------------- -- Records of grade -- ---------------------------- INSERT INTO `grade` VALUES ('lilei', 'shuxue'
, '99');
INSERT INTO `grade` VALUES ('xiaoyong', 'shuxue', '66'); INSERT INTO `grade` VALUES ('lilei', 'yingyu', '80'); INSERT INTO `grade` VALUES ('xiaoyong', 'yingyu', '55'); INSERT INTO `grade` VALUES ('lilei', 'yuwen', '78'); INSERT INTO `grade` VALUES ('xiaoyong', 'yuwen', '88');

思路
1)按照科目分組查詢成績最高的人


SELECT grade.stu_subject, MAX(grade.score) as score from grade GROUP BY stu_subject;
2)顯示出成績最高的人的姓名和科目名稱
SELECT grade.* from grade,
(SELECT grade.stu_subject, MAX(grade.score) as score from grade GROUP BY stu_subject )b
WHERE grade.score = b.score and grade.stu_subject = b.stu_subject;
3)顯示出列標題.
SELECT “成績最高”,grade.* from grade,
(SELECT grade.stu_subject, MAX(grade.score) as score from grade GROUP BY stu_subject )b
WHERE grade.score = b.score and grade.stu_subject = b.stu_subject;

成績最低的也是如此就是利用MIN()函式, 如果需要同時查出, 可以用union 如下sql

SELECT "成績最高",grade.* from grade, 
(SELECT  grade.stu_subject, MAX(grade.score) as score  from grade GROUP BY  stu_subject  )b
WHERE grade.score = b.score and grade.stu_subject = b.stu_subject
UNION
SELECT "成績最低",grade.* from grade, 
(SELECT  grade.stu_subject, MIN(grade.score) as score  from grade GROUP BY  stu_subject  )b
WHERE grade.score = b.score and grade.stu_subject = b.stu_subject;

查詢結果如下圖所示:
這裡寫圖片描述

總結:
路漫漫其修遠兮,吾將上下而求索。