有这样一个表
学号   班级   成绩
-------------------------
1     1      70
2     1      71
3     1      72
4     2      73
5     2      74
6     2      75想得到每个班级成绩最高的那个人的学号,当然成绩有可能相等学号   班级   成绩
-------------------------
3     1     72
6     2     75select max(成绩)
from 表
group by 班级 可是这样得不到学号呀比如我想给每个班成绩最好的人的成绩再加上他的课外成绩,这就需要那学号当主键

解决方案 »

  1.   

    create table #tbb(xuhao int,banji varchar(100),chengji int)
    insert into #tbb
     select 1,'1',70
    union all select 2,'1',71
    union all select 3,'1',72
    union all select 4,'2',73
    union all select 5,'2',74
    union all select 6,'2',75;with cte as
    (
    select rank() over ( partition by banji  order by chengji desc)ID,xuhao,banji,chengji from #tbb
    )
    select xuhao,banji,chengji from cte where ID=1
      

  2.   

    create table test(学号 int,班级 int,成绩 tinyint)
    go
    insert into test
     select 1,'1',70
    union all select 2,'1',71
    union all select 3,'1',72
    union all select 4,'2',73
    union all select 5,'2',74
    union all select 6,'2',75
    go
    select * from test select 学号,班级,成绩 from test --如果只需学号,则班级,成绩可不写
     where 成绩 in 
    (select max(成绩) from test group by 班级)学号          班级          成绩
    ----------- ----------- ----
    3           1           72
    6           2           75(2 行受影响)
      

  3.   


    拍砖啦 呵呵 有些不严谨

    有这样一个表
    学号   班级   成绩
    -------------------------
    1     1      70
    2     1      71
    3     1      72
    4     2      73
    5     2      72
    6     2      75这样的数据就会出错
    还是1楼的号点来点笨方法select * from test where 学号 in(select 学号 from test where cast(班级 as nvarchar(100))+cast(成绩 as nvarchar(100)) in(select cast(班级 as nvarchar(100))+cast(max(成绩)as nvarchar(100)) as flag from test group by 班级) )
      

  4.   


    create table cj(学号 int, 班级 int, 成绩 int)insert into cj
     select 1, 1, 70 union all
     select 2, 1, 71 union all
     select 3, 1, 72 union all
     select 4, 2, 73 union all
     select 5, 2, 74 union all
     select 6, 2, 75
    -- 写法1
    select * 
     from cj a
     where not exists(select 1 from cj b 
                      where b.班级=a.班级 and b.成绩>a.成绩)/*
    学号          班级          成绩
    ----------- ----------- -----------
    3           1           72
    6           2           75(2 row(s) affected)
    */
    -- 写法2
    select 学号,班级,成绩 from
    (select 学号,班级,成绩,
            rank() over(partition by 班级 order by 成绩 desc) 'rn' 
     from cj) t
    where rn=1/*
    学号          班级          成绩
    ----------- ----------- -----------
    3           1           72
    6           2           75(2 row(s) affected)
    */
      

  5.   

    select 学号,班级,成绩 from test t  --如果只需学号,则班级,成绩可不写
     where 成绩=
    (select max(成绩) from test where 班级=t.班级)