我把表缩写成stu(sid varchar(8), cid varchar(10), score int), 这样可以不?要不要考虑并列情况我的意思是:如果A在数学拿了最高分90, B和C拿了次高分89。这样的话, 如何输出?
A, B, C还是A, B, 还是A, C?

解决方案 »

  1.   

    --测试数据
    create table stu(sid varchar(8), cid varchar(10), score int)
    insert stu select '001', '001', 90
    union  all select '002', '001', 89
    union  all select '003', '001', 89
    union  all select '004', '001', 80
    union  all select '001', '002', 92
    union  all select '002', '002', 93
    union  all select '003', '002', 88
    --查询(考虑并列的情况)
    select sid, cid, score
    from (
    select *
          ,id=(select count(*)+1 from stu
             where cid=tt.cid and score>tt.score)
    from stu as tt)t
    where t.id<=2
    order by cid, score desc
    --清除
    drop table stu
      

  2.   

    连并列一起输出:
    create table stu(sid varchar(8), cid varchar(10), score int)
    insert stu select '001', '001', 90
    union  all select '002', '001', 89
    union  all select '003', '001', 89
    union  all select '004', '001', 80
    union  all select '001', '002', 92
    union  all select '002', '002', 93
    union  all select '003', '002', 88select * from stu order by cid,scoreselect A.* from stu A where not exists(select 1 from stu where cid=A.cid and score>A.score having count(*)>1) drop table stu
      

  3.   

    SELECT *
    FROM stu a
    WHERE ((SELECT COUNT(*)
              FROM stu b
              WHERE a.cid = b.cid AND a.score < b.score) < 2)
    ORDER BY score DESC