Rownum语句返回不同于它的行

时间:2015-04-02 10:14:37

标签: sql oracle

好的,所以我有这个select语句,它返回具有最少人数的部门编号,但由于数据库中的数据,它返回两个部门。当我添加rownum = 1时,它给了我一个完全不同的部门编号,它拥有最多的CLERKS,我不知道为什么会这样做。帮助赞赏

select deptno from emp where job='CLERK' group by deptno 
having count(job)=(select min(count(job)) from emp where job='CLERK'group by deptno);

我尝试在主select语句和sub select语句中使用rownum但结果相同..我甚至使用了order by,它仍然产生了相同的结果。

select deptno from emp where rownum=1 and job='CLERK' group by deptno 
having count(job)=(select min(count(job)) from emp where job='CLERK'group by deptno) order by deptno;

以下是rownum和order by的相同陈述。

2 个答案:

答案 0 :(得分:1)

您的问题是由where之前应用order by子句引起的。

您可以先排序,然后应用rownum

来解决问题
select * from (
    select deptno from emp 
     where job='CLERK' 
     group by deptno 
    having count(job)=(select min(count(job)) from emp where job='CLERK'group by deptno) 
     order by deptno) 
where rownum=1;

注意:

此问题是Oracle特有的。 MS SQL Server TOP和MySQL LIMIT都在order by子句之后应用。

注2:

In Oracle Database 12c (12.1), there is a new feature for selecting rows k through k+moffset k rows fetch next m rows only。我建议使用它而不是上面的解决方案。感谢Lalit Kumar B指出它。

select deptno from emp 
 where job='CLERK' 
 group by deptno 
having count(job)=(select min(count(job)) from emp where job='CLERK'group by deptno) 
order by deptno
fetch next 1 rows only

但是,如果有两个(或更多)部门具有相同的编号怎么办?别担心,有一种变体会返回所有联系:

select deptno from emp 
 where job='CLERK' 
 group by deptno 
having count(job)=(select min(count(job)) from emp where job='CLERK'group by deptno) 
order by deptno
fetch next 1 rows with ties

答案 1 :(得分:1)

按照@Klas的另一个答案:

Oracle 12c 中,您可以使用新的前N行限制功能

例如,

SQL> SELECT empno, sal FROM emp ORDER BY sal DESC;

     EMPNO        SAL
---------- ----------
      7839       5000
      7902       3000
      7788       3000
      7566       2975
      7698       2850
      7782       2450
      7499       1600
      7844       1500
      7934       1300
      7521       1250
      7654       1250
      7876       1100
      7900        950
      7369        800

14 rows selected.

SQL> SELECT empno, sal
  2  FROM emp
  3  ORDER BY sal DESC
  4  FETCH FIRST 5 ROWS ONLY;

     EMPNO        SAL
---------- ----------
      7839       5000
      7788       3000
      7902       3000
      7566       2975
      7698       2850