Oracle rownum 1无法正常工作

时间:2012-10-03 06:43:34

标签: database oracle

我有oracle的问题只是用限制创建简单的选择但是oracle没有得到这个功能所以我写了类似的东西

     select b.strdir,b.num, b.value, b.time  

          from mytable b
         where b.dev_id = 223
           and b.cur_id = 23
           and b.time=(
                select xx.time from mytable xx
                where xx.dev_id = b.dev_id and xx.cur_id = b.cur_id and xx.nom = b.nom
                and rownum=1
                order by xx.time DESC
               )

         order by b.strdir nulls first;

但它没有工作PLZ帮助:/

4 个答案:

答案 0 :(得分:4)

这种类型的查询最好使用第一个/最后一个聚合函数(也称为“keep子句”)来处理,尽管我还没有测试过查询。

select max(b.strdir) keep (dense_rank last order by b.time) strdir
     , max(b.num) keep (dense_rank last order by b.time) num
     , max(b.value) keep (dense_rank last order by b.time) value
     , max(b.time) time  
  from mytable b
 where b.dev_id = 223
   and b.cur_id = 23
 group by b.nom
 order by strdir nulls first

http://rwijk.blogspot.com/2012/09/keep-clause.html

的问候,
罗布。

答案 1 :(得分:1)

Oracle在一行传递谓词后指定rownum,因此你的where子句永远不会让任何东西通过。在oracle中选择TOP n的规范方法是:

select * from ( <your statement> ) where rownum <= N

答案 2 :(得分:1)

要获取具有最近时间的dev_id,row_id对,请使用:

 select b.strdir,b.num, b.value, b.time  
      from mytable b
     where b.dev_id = 223
       and b.cur_id = 23
       and b.time =(
            select max(xx.time) from mytable xx
            where xx.dev_id = b.dev_id and xx.cur_id = b.cur_id 
              and xx.nom = b.nom --> not sure this line is necessary
           )
     order by b.strdir nulls first;

请注意,在应用ROWNUM = 1时,SORT BY子句会被忽略,因为SORT BYWHERE后完成了。解决方案是使用MAX(time)是子查询来查找最新时间。

还要注意返回重复行的风险,如果行可能具有相同time值的行。一种可能的解决方案是在外部SQL中使用SELECT DISTINCT

答案 3 :(得分:0)

    select b.strdir,b.num, b.value, b.time  

      from mytable b
     where b.dev_id = 223
       and b.cur_id = 23
       and b.time=(
            select max(xx.time) from mytable xx
            where xx.dev_id = b.dev_id and xx.cur_id = b.cur_id and xx.nom = b.nom

           )

     order by b.strdir nulls first;
这是好版本吗? max(xx.time)