select in_time from work_task 
where (state=190) and in_time>to_date(to_char(add_months(sysdate,-12),'yyyy-mm'),'yyyy-mm')  and rownum<=1 order by in_time desc查出的数据是:
2010-03-23 17:31:17删除rownum<=1后查出来的数据是
2010-03-23 22:39:33
2010-03-23 17:43:31
2010-03-23 17:31:17为什么有加rownum<=1时,不是查出2010-03-23 22:39:33??

解决方案 »

  1.   

    你的需求,rownum和order by不能同时取。
    先order by,再取rownum<=1。select in_time from
       (select in_time,rownum rn from work_task 
        where (state=190) and in_time>to_date(to_char(add_months(sysdate,-12),'yyyy-mm'),'yyyy-mm') order by in_time desc)
    where rn<=1;
      

  2.   

    因为order by 是在查询结果出来后,才进行排序的!所有这里先执行了rownum<=1,也就是sql查询结果随机排序取的第一个,这时您再排序其实是只针对这一条结果进行排序的!您是不是想要排序后取第一个,可以试试:
    select * from(
    select in_time from work_task 
    where (state=190) and in_time>to_date(to_char(add_months(sysdate,-12),'yyyy-mm'),'yyyy-mm') order by in_time desc) where rownum<=1 
      

  3.   

    with t_test as(
    select to_date('2010-03-23 22:39:33','yyyy-mm-dd hh24:mi:ss') dd from dual union all
    select to_date('2010-03-23 17:43:31','yyyy-mm-dd hh24:mi:ss') from dual union all
    select to_date('2010-03-23 17:31:17','yyyy-mm-dd hh24:mi:ss') from dual)
    select * 
    from (select * from t_test
    order by dd desc)
    where rownum = 1;