不是写了吗??declare @ table (a int,b int)
insert @ values(1,1)
insert @ values(1,2)
insert @ values(1,3)
insert @ values(1,4)
insert @ values(1,5)
insert @ values(1,6)
insert @ values(2,1)
insert @ values(2,2)
insert @ values(2,3)
insert @ values(2,34)
insert @ values(2,4)
insert @ values(2,9)select  * from @ aa where exists( select 1 from (select top 5 * from @ where a=aa.a order by b desc) tem where tem.b=aa.b)

解决方案 »

  1.   

    select  * from 表 aa where exists( select 1 from (select top 5 * from 表 where 班级=aa.班级 order by 身高 desc) tem where tem.身高=aa.身高)
      

  2.   

    这是一个典型的top-group的问题(就是在每个group里取top),我也遇到很多次,我原来采用的是直译的方法,就是根据要求直接写
    select * from 学生 s where (select count(*) from 学生 s2 where s2.班号=s.班号 and s2.身高>s.身高)<5
    这个方法是最容易想出来的,而且也完全达到了要求。
    但是!你在查询分析器中可以看到这个查询其实进行了很多的重绕操作。在你要求的top数量增加以及整个表记录增加的情况下,查询耗费的时间直线上升我现在想出的方法是用临时表或临时变量,具体效率如何没试过,但想来应该比上面的好具体的语句就不写了,主要想法是:
    1。先使用group by 查找出所有的班号(使用游标)
    2. 对于每个班号,取出身高前5位放入临时表
    3. select 临时表不过,以前看到有人说t-sql里所有使用游标的地方都可以不使用游标 
      

  3.   

    select top 5 * from table1 order by height