将Rownum与不同的结合起来

时间:2018-01-22 12:06:53

标签: oracle distinct rownum

我在Oracle中有这个查询:

Select run_date 
from (select distinct run_date 
      from transactions where primary_customer_id ='cliente'
      group by run_date 
      order by run_date desc);

我需要显示第二行,但行数不可能。

Select run_date, rownum r_ from(select distinct run_date 
                              from transactions 
                              where primary_customer_id ='cliente' 
                              group by run_date 
                              order by run_date desc))
where r_ = 2;

我可以帮助我吗?

非常感谢。

3 个答案:

答案 0 :(得分:1)

您无需同时使用GROUP BYDISTINCT。另请注意,Oracle中永远不会满足简单的ROWNUM = 2

这适用于10g和11g。

WITH r
     AS (  SELECT DISTINCT run_date
             FROM transactions
            WHERE primary_customer_id = 'cliente'
         ORDER BY run_date DESC)
SELECT run_date
  FROM (SELECT run_date, ROWNUM rn FROM r)
 WHERE rn = 2;

在Oracle 12c中,您可以使用这样的查询获得相同的结果。

 SELECT run_date
    FROM r  -- without ORDER BY inside cte, r
ORDER BY run_date DESC
  OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;

答案 1 :(得分:0)

你不应该在使用rownum而不是别名r _

的地方使用别名
Select run_date, rownum r_ from(
      select distinct run_date 
      from transactions 
      where primary_customer_id ='cliente' 
      order by run_date desc)) t
where rownum = 2; 

并且使用distinct您不需要分组。

分组依据聚合函数为min()max()count()...

你可以在没有子查询的情况下直接尝试

      select distinct run_date 
      from transactions 
      where primary_customer_id ='cliente' 
      and rownum =2
      order by run_date desc

答案 2 :(得分:0)

rownum可能,但需要一些准确性:

select run_date
from 
  ( select run_date, rownum r# 
    from 
      ( select run_date 
        from transactions 
        where primary_customer_id ='cliente' 
        group by run_date 
        order by run_date desc
      )
  )
where r# = 2;

太糟糕了,虽然它确实有效,但没人能保证它会永远存在。此查询的结果在理论上是不可预测的,使用它的技巧可能会在新版本的RDBMS内核中失败,就像Oracle 10g和GROUP BY排序一样。所以使用像

这样的东西会更好
select min(run_date)
from 
  ( select lead(run_date) over (order by run_date) run_date
    from 
      ( select distinct run_date 
        from transactions 
        where primary_customer_id ='cliente'
      )
  )
where r# = 2;

P.S。无论如何,像你一样将DISTINCT与GROUP BY结合起来就是口吃。