group by, having, where

基础的东西长久不用太容易丢了,或者是自己理解不深刻。。。
就是一个题目,一张分数表,有学号,课程号,分数,求每门课程分数最大的学生学号。
表:score(stu_id varchar2(10), course_id varchar2(20), score number)
sql:
select s.stu_id, s.course_id,s.score
    from (select course_id, max(score) as score from score group by course_id) t, score s
       where t.course_id = s.course_id and t.score = s.score;

1)先要分组,查出每门课程的最大分数和课程号。
2)再复合查询,拼接条件查出学号。

又有一张表student(id number, name varchar2(20))同时还要查出姓名:

select s.stu_id, st.name, s.course_id,s.score
    from (select course_id, max(score) as score from score group by course_id) t, score s, student st
       where t.course_id = s.course_id and t.score = s.score and st.id = s.stu_id;
或者   
select * from ( select s.stu_id, s.course_id,s.score
    from (select course_id, max(score) as score from score group by course_id) t, score s
       where t.course_id = s.course_id and t.score = s.score) stt left join student st on st.id = stt.stu_id;
刚开始看到这个死活是没搞出来,悲哀。。
----------------------------
说到group by, select 后面的字段只能是聚集函数或group by后面出现的字段,其他字段带上的结果都不正确,但不会报错。
可以在group by之前用where先把不符合条件的记录排除掉,也可以在group by之后用having来过滤结果,having后面只能针对分组使用聚集函数。
where执行的优先级在聚合函数之前。

猜你喜欢

转载自zoroeye.iteye.com/blog/1935014