rownum 和 order by 的问题?

ruanwxh 2010-03-26 09:08:47

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??
...全文
45 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ORHCLE 2010-03-26
  • 打赏
  • 举报
回复
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;
lx978 2010-03-26
  • 打赏
  • 举报
回复
因为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

suiziguo 2010-03-26
  • 打赏
  • 举报
回复
你的需求,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;

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧