leetcode -- sql -- 獲取各課程第二高成績的人的信息

-- 表結構

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
  `student_id` int(11) NOT NULL COMMENT '學生id',
  `class_id` int(11) NOT NULL COMMENT '學科id',
  `score` int(11) NOT NULL COMMENT '成績',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

 

-- 第一步 : 獲得各個部門成績最高的數值


SELECT MAX(score) score , class_id
                                from student
                                GROUP BY class_id


-- 第二部 :將查出來的子表和原來的表關聯查詢,查詢出每科目最大分數的人


SELECT b.*
FROM (
                SELECT MAX(score) score , class_id
                        from student
                        GROUP BY class_id
            )a
LEFT JOIN student b on a.class_id = b.class_id and a.score = b.score


-- 第三步 :獲得各個部門第二高的成績的人,就是將第二部獲得的人排除掉,然後獲得最大


SELECT MAX(score) score , class_id
from student
where id not in (
                                    SELECT b.id
                                    FROM (
                                        SELECT MAX(score) score , class_id
                                                from student
                                                GROUP BY class_id
                                    )a
                                    LEFT JOIN student b on a.class_id = b.class_id and a.score = b.score
                                )
GROUP BY class_id

 

-- 第四部 :根據第二大的成績和課程id獲得所有信息

 

SELECT b.*
FROM (
                SELECT MAX(score) score , class_id
                from student
                where id not in (
                                                    SELECT b.id
                                                    FROM (
                                                        SELECT MAX(score) score , class_id
                                                                from student
                                                                GROUP BY class_id
                                                    )a
                                                    LEFT JOIN student b on a.class_id = b.class_id and a.score = b.score
                                                )
                GROUP BY class_id
            )a
LEFT JOIN student b on a.class_id = b.class_id and a.score = b.score

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章