在Oracle SQL中获取rownum = 1而不是1以外的数据

时间:2019-02-15 03:41:51

标签: sql oracle

获取结果(rownum = 1):

SELECT rownum,
       A.loadplan_name
FROM   (SELECT loadplan_name,
               run_date
        FROM   dcbp13_bia_odirepo.citizen_odi_required_loadplans
        WHERE  run_date LIKE '13-FEB-19'
        ORDER  BY run_date DESC,
                  loadplan_name ASC) A
WHERE  rownum = 1

未得到结果(rownum ≠ 1):

SELECT rownum,
       A.loadplan_name
FROM   (SELECT loadplan_name,
               run_date
        FROM   dcbp13_bia_odirepo.citizen_odi_required_loadplans
        WHERE  run_date LIKE '13-FEB-19'
        ORDER  BY run_date DESC,
                  loadplan_name ASC) A
WHERE  rownum = 2  

2 个答案:

答案 0 :(得分:3)

这在documentation中有解释。返回结果集时计算rownum。因此,它仅在将新行放入结果集中时才递增。

因此,在没有值“ 1”的情况下,它永远不会取值“ 2”。

如所解释的:

  

对ROWNUM值大于正整数的条件进行测试   总是假的。例如,此查询不返回任何行:

SELECT *
FROM employees
WHERE ROWNUM > 1;
     

提取的第一行的ROWNUM分配为1,   条件错误。现在要获取的第二行是第一行,   还为ROWNUM分配了1,并使条件为假。所有行   随后无法满足该条件,因此不会返回任何行。

解决方案通常是这样的:

SELECT rn, A.LOADPLAN_NAME
FROM (SELECT LOADPLAN_NAME, RUN_DATE, rownum as rn
      FROM DCBP13_BIA_ODIREPO.CITIZEN_ODI_REQUIRED_LOADPLANS      
      WHERE RUN_DATE like '13-FEB-19'
      ORDER BY RUN_DATE DESC, LOADPLAN_NAME ASC
     ) A  
WHERE rn = 2;

答案 1 :(得分:1)

您非常亲密。正如doco所说,对大于正整数的ROWNUM值的运算始终为false。您可以使用小于,等于而不是大于。因此,此查询可以:

SELECT rownum,
       A.loadplan_name
FROM   (SELECT loadplan_name,
               run_date
        FROM   dcbp13_bia_odirepo.citizen_odi_required_loadplans
        WHERE  run_date LIKE '13-FEB-19'
        ORDER  BY run_date DESC,
                  loadplan_name ASC) A
WHERE  rownum < 2;

SELECT rownum,
       A.loadplan_name
FROM   (SELECT loadplan_name,
               run_date
        FROM   dcbp13_bia_odirepo.citizen_odi_required_loadplans
        WHERE  run_date LIKE '13-FEB-19'
        ORDER  BY run_date DESC,
                  loadplan_name ASC) A
WHERE  rownum = 2;

但不是:

SELECT rownum,
       A.loadplan_name
FROM   (SELECT loadplan_name,
               run_date
        FROM   dcbp13_bia_odirepo.citizen_odi_required_loadplans
        WHERE  run_date LIKE '13-FEB-19'
        ORDER  BY run_date DESC,
                  loadplan_name ASC) A
WHERE  rownum > 1;