建表和插入数据语句:create table t
as
select object_name ename,
mod(object_id,50) deptno,
object_id sal
from all_objects
where rownum <= 1000用相关子查询查出每个deptno里sal最高或者最低的3个人。select *
  from t t1
 where t1.sal in (select sal
                    from (select distinct sal, deptno
                            from t b
                           where b.deptno = t1.deptno
                           order by b.deptno, b.sal desc) a
                   where rownum <= 3)

解决方案 »

  1.   


    ---查最高
    SELECT * FROM 
    (SELECT ROW_NUMBER() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) RN,T.* FROM T)
    WHERE RN<=3
    --查最低
    SELECT * FROM 
    (SELECT ROW_NUMBER() OVER(PARTITION BY DEPTNO ORDER BY SAL ) RN,T.* FROM T)
    WHERE RN<=3
     
      

  2.   

     yf520gn  用窗口函数肯定可以,但我现在的问题是为什么我用相关子查询不行?
      

  3.   


    select *
      from t t1
    where t1.sal in (select sal
                        from (select distinct sal, deptno
                                from t b
                              where b.deptno = t1.deptno
                              order by b.deptno, b.sal desc) a
                      where rownum <= 3) 
    写错了当然不行~~~
    你里面的ROWNUM<=3只取3条记录,而不是每个部门都取最高的3条记录。
    这种情况用分析函数是最方便和省力的。
      

  4.   

    但报错的地方是:t1.deptno 不是验证的列。而且我先已经排序了。
      

  5.   

    select * 
      from t t1 
    where t1.sal in (select sal 
                        from (select distinct sal, deptno 
                                from t b 
                              
                              order by b.deptno, b.sal desc) a 
                      where rownum <= 3 and b.deptno = t1.deptno ) 确可以得出正确的结果,请问这是什么原因?
      

  6.   

    FYI: 问题10
    http://topic.csdn.net/u/20081002/00/f8d90ba2-e2bb-412a-a0c5-1b6d518fc22a.html
      

  7.   

    谢谢 mantisXF
    http://topic.csdn.net/u/20081002/00/f8d90ba2-e2bb-412a-a0c5-1b6d518fc22a.html
    不过里面没有和我相关的问题。谢谢eviler
    不过select *
      from t t1
    where t1.sal in (select sal
                        from (select distinct sal, deptno
                                from t b
                              where b.deptno = t1.deptno
                              order by b.deptno, b.sal desc) a
                      where rownum <= 3 and t1.deptno=t1.deptno)也不对,而且据说是支持16层。