数据展示
---------------------------
 Id   class   sort
  1     1班    90
  2     1班    80
  3     1班    100  4     2班    50
  5     2班    90
  6     2班    89
  7     2班    85  8     3班    99
  9     3班    93
  10    3班    35  ................
---------------------------
取出  每个班级的前N个 最高分,现在没好的办法,请各位大牛看看

解决方案 »

  1.   

    select *
    from tb t
    where (select count(1) from tb where class=t.class and sort>=t.sort)<=N
      

  2.   


    --> 数据库版本:
    --> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
    --> 测试数据:[TB]
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TB]') 
    AND type in (N'U')) 
    DROP TABLE [TB]
    GO---->建表
    create table [TB]([Id] int,[class] varchar(3),[sort] int)
    insert [TB]
    select 1,'1班',90 union all
    select 2,'1班',80 union all
    select 3,'1班',100 union all
    select 4,'2班',50 union all
    select 5,'2班',90 union all
    select 6,'2班',89 union all
    select 7,'2班',85 union all
    select 8,'3班',99 union all
    select 9,'3班',93 union all
    select 10,'3班',35
    GO--> 查询结果
    select * from (
    SELECT *,ROW_NUMBER()OVER(PARTITION BY class order by sort desc ) as px 
    FROM [TB]) t
    where px<=3   --前N个--> 删除表格
    --DROP TABLE [TB]
      

  3.   

    create table tb(Id  int,class nvarchar(10),sort int)
    insert into tb select 1,'1班',90 
    insert into tb select 2,'1班',80 
    insert into tb select 3,'1班',100 
    insert into tb select 4,'2班',50 
    insert into tb select 5,'2班',90 
    insert into tb select 6,'2班',89 
    insert into tb select 7,'2班',85 
    insert into tb select 8,'3班',99 
    insert into tb select 9,'3班',93 
    insert into tb select 10,'3班',35 
    go
    --设 N = 2
    select * from tb a where id in(select top 2 id from tb where class=a.class order by sort desc)
    go
    drop table tb
    /*
    Id          class      sort
    ----------- ---------- -----------
    1           1班         90
    3           1班         100
    5           2班         90
    6           2班         89
    8           3班         99
    9           3班         93(6 行受影响)
    */
      

  4.   

    select t.* from tb t where sort in (select top N sort from tb where class = t.class order by sort desc) order by t.class , t.sort desc