日期:2014-05-17  浏览次数:20729 次

如何更简便的找出最新值
SQL code

create table sc(
    student_id char(10),
    course_id char(5),
    sc_time datetime,
    score   decimal(3)



在上面的选课表中,允许学生可以在不同的学期选择相同的一门课程(如补考等),
但如何选择出最后的那次成绩?当然创建一个视图可以满足
SQL code

create view last_sc
as
select  student_id, course_id, max(sc_time)
from sc
group by student_id, course_id;

create view last_sc_score
as
select student_id, course_id, grade
from sc left join last_sc
on sc.student_id = last_sc.student_id and sc.course_id=last_sc.student_id



可这样毕竟笨了,有么样更简便或新鲜的方法呢?忘大家指教!


------解决方案--------------------
你是 oracle 数据库吗?
------解决方案--------------------
sc_time字段表示的是什么?
既然不同学期可以选择同一门课程,那就应该在表中增加一个字段,表示学期。
------解决方案--------------------
SQL code
select student_id ,course_id ,sc_time ,score   from( 
select student_id ,course_id ,sc_time ,score  ,
row_number() over(partition by student_id ,course_id  order by sc_time  desc) rn
) where rn=1

------解决方案--------------------
SELECT *
FROM sc
 WHERE (student_id, course_id, sc_time) IN (
SELECT student_id, course_id,
MAX (sc_time) TIME
FROM sc
GROUP BY student_id, course_id)
------解决方案--------------------
SQL code

select t.* from sc t where sc_time = (select max(sc_time) from sc where student_id = t.student_id) order by t.student_id

select t.* from sc t where not exists (select 1 from sc where student_id = t.student_id and sc_time > t.sc_time) order by t.student_id

------解决方案--------------------
楼主实际上你已经自己把答案写出来了,只是差了一个知识点,就是在sql中,是可以把一个select结果集当做一个视图来使用的,所以你只要把那个视图的select语句直接放到你的sql中使用就可以了,不需要去创建这个视图。具体估法楼上几位已经给出答案了。