select top 2 * from tb_s order by 成绩 desc where 项目='铅球'
union
select top 2 * from tb_s order by 成绩 desc where 项目='跳远'
union
...........
如果项目很多的话,可以使用游标循环取出每一种项目的前两名的数据添加到一个临时表。
明天补上。

解决方案 »

  1.   

    declare a cursor for select distinct[项目] from tb_s   --声明游标,选出每一个项目
    declare %ttable table[姓名 varchar[20],项目 varchar[20],成绩 float]  --声明表变量
    declare %b varchar[20]
    open a --打开游标
    fetch nect from a into %b
    while %%fetch_status=0  '循环提取游标
      begin
      insert into %ttable
        select top 2 ^ from tb_s where 项目=%b order by 成绩 desc '将每一个项目的成绩
           前两名数据插入到表中
      fetch nect from a into %b
      end
    close a
    deallocate a
    select ^ from %ttable因键盘失效,只好用^代替星号,[]代替小括号,%代替邮箱符号
      

  2.   

    select * into test from (
    select
      'yy' as name,  '铅球' as type,  20 as score   
    union select
      'dd',  '铅球',  19   
    union select
      'sc',  '铅球',  21   
    union select
     'fdd',  '铅球',  25  
    union select 
     'dsf',  '跳远',  2.8  
    union select
     'fds',  '跳远',  3.0  
    union select
     'fds',  '跳远',  2.4 
    union select 
     'fds',  '跳远',  3.1  
    union select
     'fds',  '跳远',  3.0 ) select * from test a where a.score  in (select top 2 score from test where type = a.type order by type,score desc) order by a.type,a.score
      

  3.   

    有个小问题
    例 铅球: 姓名    项目    成绩
             a      铅球    35
             b      铅球    30
             c      铅球    30
    出现这种情况,就是有相同成绩的时候只能列出 a,b或a,c两个人,而不会把a,b,c三人都罗列出来
    这是上述几个方法都会发生的问题。解决方法:最好用存储过程完成上述任务,需要判断
      

  4.   

    ----测试用例create table #tb_s(姓名 char(20),项目 char(20),成绩 float)--建表
    goinsert #tb_s
    select 'yy' , '铅球',  20 
    union all
    select 'dd' , '铅球' , 19 
    union all 
    select  'sc' , '铅球' , 21  
    union all
    select 'fss' , '铅球' , 25
    union all
    select 'dsf' , '跳远', 2.8
    union all
    select 'fds' , '跳远', 3.0
    union all
    select 'gsf' , '跳远', 3.1
    union all
    select 'ksf' , '跳远', 2.4---插入数据
    select * from #tb_s a
    where 姓名 in(select top 2 姓名 from #tb_s b where a.项目=b.项目 order by 成绩 desc)
    order by 成绩 desc
    -----得出结果
    drop table #tb_s
    -----------删除表