xh(序号)   xm(姓名)     cj(成绩)    sj(入库时间)
1            张三           80            2010-12-01
2            李四           66            2010-12-01
3            王五           60            2010-12-01
4            张三           70            2010-12-05
5            李四           62            2010-12-05
6            王五           81            2010-12-05
7            张三           71            2010-12-10
8            李四           67            2010-12-10
9            王五           83            2010-12-10
10           张三           90            2010-12-15
11           李四           72            2010-12-15
12           王五           65            2010-12-15
上面的数据表为张三、李四、王五,三个人参加了多次考试,如何利用sql语句把三个人的最高成绩的那条记录列出,达到如下效果:
xh(序号)   xm(姓名)     cj(成绩)    sj(入库时间)
10           张三           90            2010-12-15
11           李四           72            2010-12-15
9            王五           83            2010-12-10

解决方案 »

  1.   

    select * from ( select a.*,row_number(partition by xm order by cj desc) rn from tab)
    where rn=1;
      

  2.   

    select xh,xm,cj,sj from tab
    where (xm,cj) = (select xm,max(cj) from tab group by xm )
      

  3.   

    如果是数据量很大的情况下
    select xh,xm,cj,sj from tab
    where (xm,cj) = (select xm,max(cj) from tab group by xm )
    执行很慢啊。还有没有更加优化的SQL啊?
      

  4.   

    select * from ( select a.*,row_number(partition by xm order by cj desc) rn from tab)
    where rn=1;报ORA-00907的错误啊。
      

  5.   


    with t as(
    select 1 xh,'张三' xm,80 cj,'2010-12-01' sj from dual
    union all
    select 2,'李四',66,'2010-12-01' from dual
    union all
    select 3,'王五',60,'2010-12-01' from dual
    union all
    select 4,'张三',70,'2010-12-05' from dual
    union all
    select 5,'李四',62,'2010-12-05' from dual
    union all
    select 6,'王五',81,'2010-12-05' from dual
    union all
    select 7,'张三',71,'2010-12-10' from dual
    union all
    select 8,'李四',67,'2010-12-10' from dual
    union all
    select 9,'王五',83,'2010-12-10' from dual
    union all
    select 10,'张三',90,'2010-12-15' from dual
    union all
    select 11,'李四',72,'2010-12-15' from dual
    union all
    select 12,'王五',65,'2010-12-15' from dual
    )
    select *
      from t t1
     where not exists (select 1
              from t t2
             where t2.xm = t1.xm
               and t1.cj < t2.cj)
    9 王五 83 2010-12-10
    10 张三 90 2010-12-15
    11 李四 72 2010-12-15