这个问题困扰我一天了。
用一个SQL查询语句得出每门功课成绩最好的前两名 学号  功课编号        学生成绩 
1          1            99 
2          1            98 
3          1            100 
4          2            88 
5          2            87 
6          2            88
7          2            70
7          3            99 
8          3            88 
9          3            100 
网上给的答案是用自连接。SELECT  学生表1.* 
FROM 学生表 学生表1 where 学生表1.学号 IN 
(SELECT TOP 2 学生表.学号 
FROM 学生表 
WHERE 学生表.功课编号 = 学生表1.功课编号 
ORDER BY 学生成绩 DESC) 可是我是看不懂他是怎么连接的。尤其是top 2 不是只会得到两条记录吗。怎么会是每个功课编号的前两名(按以前我们写的不管是几个表总会就两条记录)。还有就是如果查询出来了前两位。比方说功课编号3的前两位是9.7  条件里面是学号 in 那查询出的结果不是把 7 2 70 的记录也会查出来了吗?可是结果并没有查出来。盼高手来解析。

解决方案 »

  1.   

    select t.* from tb t where 学生成绩 in (select top 2 学生成绩 from tb where 功课编号 = t.功课编号 order by 学生成绩 desc)
      

  2.   

    WHERE 学生表.功课编号 = 学生表1.功课编号 这个条件不要忘了啊
      

  3.   

    WHERE 学生表.功课编号 = 学生表1.功课编号 在子查询中查的就是同一门课程的,然后top2 ,order by desc 自然是该课程的前两位
      

  4.   

    create table tb(学号 int, 功课编号 int, 学生成绩 int)
    insert into tb values(1 , 1 , 99 )
    insert into tb values(2 , 1 , 98 )
    insert into tb values(3 , 1 , 100) 
    insert into tb values(4 , 2 , 88 )
    insert into tb values(5 , 2 , 87 )
    insert into tb values(6 , 2 , 88 )
    insert into tb values(7 , 2 , 70 )
    insert into tb values(7 , 3 , 99 )
    insert into tb values(8 , 3 , 88 )
    insert into tb values(9 , 3 , 100)
    goselect t.* from tb t where 学生成绩 in (select top 2 学生成绩 from tb where 功课编号 = t.功课编号 order by 学生成绩 desc) order by t.功课编号 , t.学生成绩 descdrop table tb/*
    学号          功课编号        学生成绩        
    ----------- ----------- ----------- 
    3           1           100
    1           1           99
    4           2           88
    6           2           88
    9           3           100
    7           3           99(所影响的行数为 6 行)
    */ 
      

  5.   

    select 
      * 
    from 
      tb t 
    where 
      学生成绩 in (select top 2 学生成绩 from tb where 功课编号 = t.功课编号 order by 学生成绩 desc) 
    order by 
      t.功课编号 , t.学生成绩 desc
      

  6.   

    执行顺序是这样的 先order by 再TOP 2