SQL:求总分最高的学生

CREATE TABLE course ( id INTEGER PRIMARY KEY, NAME TEXT NOT NULL );
CREATE TABLE student ( id INTEGER PRIMARY KEY, NAME TEXT NOT NULL );
CREATE TABLE score ( id INTEGER PRIMARY KEY, course_id INTEGER NOT NULL, student_id INTEGER NOT NULL, score INTEGER NOT NULL );

INSERT INTO course VALUES(1,'语文'),(2,'数学'),(3,'外语');
INSERT INTO student VALUES(1,'小张'),(2,'小王'),(3,'小马');

INSERT INTO score VALUES(1 ,1 ,1 ,80),(2 ,2 ,1 ,90),(3, 3, 1, 70);
INSERT INTO score VALUES(4 ,1 ,2 ,70),(5 ,2 ,2 ,90),(6, 3, 2, 80);
INSERT INTO score VALUES(7 ,1 ,3 ,80),(8 ,2 ,3 ,60),(9, 3, 3, 70);

-- 求总分最高的学生  (搞清楚是要全部学科的总分,还是单科总分最高?)
-- 思路:使用SUM函数 + 学生ID分组获取最高分
SELECT SUM(score) from score GROUP BY student_id ORDER BY SUM(score) desc  LIMIT 1


-- 这样只能查出一个人的最高分的,但是万一最高分有两个人或更多呢?     查出最高分所有的student
SELECT student_id from score GROUP BY student_id HAVING SUM(score) = (SELECT SUM(score) from score GROUP BY student_id ORDER BY SUM(score) desc  LIMIT 1)

-- 然后join 查出最高分的学生
SELECT s.name, t.score from student s RIGHT JOIN (SELECT student_id, SUM(score) score from score GROUP BY student_id HAVING SUM(score) = (SELECT SUM(score) from score GROUP BY student_id ORDER BY SUM(score) desc  LIMIT 1)) t ON s.id = t.student_id;

-- 如果需求是求单科最高分,该怎么写?
-- 先根据course_id分组,求出单科最高分
SELECT course_id, MAX(score) max_score from score GROUP BY course_id

-- 然后再查出 取得这个最高分的所有学生
SELECT student_id , s1.course_id, s2.max_score from score s1 RIGHT JOIN (SELECT course_id, MAX(score) max_score from score GROUP BY course_id) s2 
ON s1.score = s2.max_score and s1.course_id = s2.course_id;

-- 最后关联学生表和课程表 查找出对应的名字
SELECT s.name, c.name, s2.max_score from score s1 RIGHT JOIN (SELECT course_id, MAX(score) max_score from score GROUP BY course_id) s2 
ON s1.score = s2.max_score and s1.course_id = s2.course_id
LEFT JOIN student s ON s.id = s1.student_id
LEFT JOIN course c ON c.id = s1.course_id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值