id         class
---------- ---------- 
6          a         
3          a         
7          a         
4          a         
2          a         
5          b         
2          b         
1          b         
6          b         
3          b         
6          b         
7          b
...       ...  
求出a,b... 的前三条最大的id?

解决方案 »

  1.   

    参考:分类取前两名create table A(Score int ,Shift varchar(10))
    insert A
    select 20,'B' union all
    select 30,'B' union all
    select 10,'B' union all
    select 78,'A' union all
    select 19,'A' union all
    select 5 ,'A' union all
    select 40,'C' union all
    select 25,'C' union all
    select 6 ,'C'
    --select * from Acreate table B(Score int,Shift varchar(10))
    insert B select 20,'B'
    --select * from Bselect * from A i
    where score in 
    (
    select top 2 score from A where Shift=i.Shift and score not in(select score from B where Shift=A.Shift)
    )drop table A,B
      

  2.   

    select a.[id]
    from tablename a
    where (select count(1) from tablename where class = a.class and [id] < a.[id]) < 3
      

  3.   

    反了,最大的应该是:
    select a.*
    from tablename a
    where (select count(1) from tablename where class = a.class and [id] > a.[id]) < 3
      

  4.   

    select 
        t.* 
    from 
        表 t 
    where 
        t.id in(select top 3 id from 表 where class=t.class order by id desc)