oracle中取前几条数据&TRUNC()函数

在oracle中查表中的前10条数据---- select * from test where rownum <= 10 ;  rownum是把SQL出来的结果进行编号,始终从1开始,常见的用途就是用来分页。类似于MYSQL和SQL SERVER的top。

select * from (select a.*,rownum rn from test a) where rn >=10 and rn<=20; 输出10到20条语句。因为rownum本身只能用<=的比较方式,只有转成实例才能用>=的比较方式。

实际用途中,常常回求最近的几条数据,需要对数据进行排序后在去rownum<=

方式一:任何时候都成立:select * from(select a.* from test a order by order_date desc ) where rownum <= 10

方式二:只有在以主键进行排序时执行顺序才是先排序在取10条,其余的都是先取10条在排序。

综合在以主键进行排序时方式二效率要高很多。否则只能用方式一。

对于分组后编号rownum是不能实现的。这时 row_num() over(partition by 分组字段 order by 排序字段) 就能实现分组编号。ROW_NUMBER() OVER(partition by col1 order by col2) 表示根据col1分组,在分组内部根据col2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内是连续且唯一的)。 

举例:取近一个月的每天最后10个订单记录: select * from ( select a.* , row_num() over(partition by trunc(order_date) order by order_date desc) rn from test a ) where rn <=10;

rownum的另类用法:有时候我们会遇到这样的需求,要求输出当月的所有天数,但是数据库里没有这样的表怎么输出呢?

select trunc(SYSDATE,'MM')+rownum-1 from dual connect by rownum <= TO_NUMBER (TO_CHAR (LAST_DAY (SYSDATE), 'dd'))

trunc()函数的用法:

日期:

1.select trunc(sysdate) from dual  --2011-3-18  今天的日期为2011-3-18
2.select trunc(sysdate, 'mm')   from   dual  --2011-3-1    返回当月第一天.
3.select trunc(sysdate,'yy') from dual  --2011-1-1       返回当年第一天
4.select trunc(sysdate,'dd') from dual  --2011-3-18    返回当前年月日
5.select trunc(sysdate,'yyyy') from dual  --2011-1-1   返回当年第一天
6.select trunc(sysdate,'d') from dual  --2011-3-13 (星期天)返回当前星期的第一天
7.select trunc(sysdate, 'hh') from dual   --2011-3-18 14:00:00   当前时间为14:41   
8.select trunc(sysdate, 'mi') from dual  --2011-3-18 14:41:00   TRUNC()函数没有秒的精确

数字:

/*
TRUNC(number,num_digits) 
Number 需要截尾取整的数字。 
Num_digits 用于指定取整精度的数字。Num_digits 的默认值为 0。
TRUNC()函数截取时不进行四舍五入
*/
9.select trunc(123.458) from dual --123
10.select trunc(123.458,0) from dual --123
11.select trunc(123.458,1) from dual --123.4
12.select trunc(123.458,-1) from dual --120
13.select trunc(123.458,-4) from dual --0
14.select trunc(123.458,4) from dual  --123.458
15.select trunc(123) from dual  --123
16.select trunc(123,1) from dual --123
17.select trunc(123,-1) from dual --120

rank()是跳跃排序,有两个第二名时接下来就是第四名(同样是在各个分组内) 
dense_rank()也是连续排序,有两个第二名时仍然跟着第三名。相比之下row_number是没有重复值的。

原文地址:https://www.cnblogs.com/dobestself-994395/p/4264104.html