表结构:
MS SQL                       
Create table #temp
(
ID int,
name varchar(20),
age int,
cid int
)Oracle
Create global temporary table temp
(
ID int,
name varchar(20),
age int,
cid int
)
查询出每个班级(cid)年龄最小的前两位同学信息
MS SQL:select * from #temp a
where id in
(
select top 2 id from #temp
where a.cid=cid
order by age asc
)
没问题
Oracle:select *
from scott.student a
where sid in
(
select sid
from 
(
select sid
from scott.student
where a.cid=cid
order by age asc
) b
where rownum<=2
)
只能得到所有记录中年龄最小的两条记录为什么??

解决方案 »

  1.   

    in里的语句是子查询,招行完主程序才会招行,可以考虑用exist试试
      

  2.   

    基本想法都一样,根据外层查询的cid(班级号),子查询会查询出相应的年龄最小的两个sid(学号),如果外层查询的sid正好符合子查询的某一个sid,就将其放入结果集。但为什么同样的方法MS SQl 可以实现,但Oracle不行呢??
      

  3.   

    你用的oracle版本是多少?我在oracle 10g下运行的时候会报错,说是a.cid无效。
      

  4.   

    难道MS SQL和Oracle在解析的时候算法不同吗?
      

  5.   

    select * from scott.student a
    where sid in (select sid from 
    (select * from scott.student order by age asc)
    where a.cid=cid and rownum<=2)这样写就对了.
      

  6.   

    关键是 a.cid=cid and rownum<=2 这两个条件不能分开.
      

  7.   

    SELECT
        *
    FROM
        (SELECT
            a.*,
            row_number() over(partition by a.cid order by a.age asc) num
        FROM
            scott.student a
        )
    WHERE
        num <= 2