现有一个学生成绩表Table(ID,S_ID'学员编号,score'成绩,subject'科目)想得到的查询结果是:查出每科成绩前三名的成绩信息。

解决方案 »

  1.   

    select 
      *
    from
      [Table] t
    where
      (select count(1) from [Table] where subject=t.subject and score>=t.score)<=3
      

  2.   

    select *from [Table] t
    where 3>=(select count(1) from [Table] where subject=t.subject and score>=t.score)
      

  3.   


    select * from tb a  where id in (select top 3 id from tb where subject=a.subject order by score desc)
      

  4.   

    if object_id('[tb]') is not null drop table [tb] 
     go 
    create table [tb]([ID] int,score int,subject varchar(10))
    insert [tb] select 1,90,'A'
    union all select   2,98,'A'
    union all select   3,99,'A'
    union all select   4,33,'A'
    union all select   5,97,'A'
    union all select   6,98,'B'
    union all select   7,99,'B'select * from tb a  where id in (select top 3 id from tb where subject=a.subject order by score desc) 
    /*
    2 98 A
    3 99 A
    5 97 A
    6 98 B
    7 99 B
    */
      

  5.   

    DECLARE @t TABLE(id int ,s_id char(4),subject varchar(10),score int )
    INSERT @t SELECT 1,'011','英语', 99
    UNION ALL SELECT 2,'011','数学', 88
    UNION ALL SELECT 3,'011','物理',99UNION ALL SELECT 4,'012','英语', 55
    UNION ALL SELECT 5,'012','数学',  77
    UNION ALL SELECT 6,'012','物理', 88UNION ALL SELECT 7,'013','英语',66
    UNION ALL SELECT 8,'013','数学', 55
    UNION ALL SELECT 9,'013','物理',  77UNION ALL SELECT 10,'014','英语',33
    UNION ALL SELECT 11,'014','数学', 100
    UNION ALL SELECT 12,'014','物理', 55select s_id,subject,score  into #tt
    from @T t
    where 3>=(select count(1) from @T where subject=t.subject and score>=t.score)
    group by s_id,subject,score
    --查询
    select * from #tt
    --行列转换
    select * 
    from #tt  a pivot (max(score) for subject in(英语,物理,数学)) b
    结果:
    S_id   英语 物理 数学
    011  99 99 88
    012  55 88 77
    013  66 77 NULL
    014  NULL NULL 100