首页 > 代码库 > Oracle的over子函数的妙用

Oracle的over子函数的妙用

摘要

  • oracle的over 子函数可实现按指定的字段分组排序,对于相同分组字段的结果集进行排序,其中PARTITION BY 为分组字段,ORDER BY 指定排序字段这对统计分析这类问题意想不到的效果.
  1. over函数的妙用

      例1: 累计求和

select fdate 日期,total 金额,tax 税额,
sum(total) over (order by fdate) 累计金额,sum(tax) over (order by fdate) 累计税额 
from
( select fildate fdate,sum(total) total,sum(tax) tax from stkin t group by fildate )
order by fdate;

      例2:累计求和月分组统计

select fdate 日期,total 金额,tax 税额,
sum(total) over (order by fdate) 累计金额,sum(tax) over (order by fdate) 累计税额,
sum(total) over (partition by yymm order by fdate) 本月累计金额,
sum(tax) over (partition by yymm order by fdate) 本月累计税额,yymm from (select fildate fdate,to_char(fildate,yyyy-mm) yymm,sum(total) total,sum(tax) tax from stkin t group by fildate)
order by fdate,yymm;

      例3:占比计算

select fdate 日期,total 金额,tax 税额,
sum(total) over (order by fdate,yymm) 累计金额,sum(tax) over (order by fdate,yymm) 累计税额,
sum(total) over (partition by yymm order by fdate,yymm) 本月累计金额,sum(tax) over (partition by yymm order by fdate,yymm) 本月累计税额,
sum(total) over () 累计金额,
100*round(total/sum(total) over (),4) 占比,
100*round(total/sum(total) over (partition by yymm),4) 月占比,yymm
from (select fildate fdate,to_char(fildate,yyyy-mm) yymm,sum(total) total,sum(tax) tax from stkin t group by fildate) 
order by fdate,yymm;

      注1:partition by 表示分组

      注2:在"... from emp;"后面不要加order by 子句,使用的分析函数的(partition by yymm order by fdade,yymm)里已经排序的语句了,如果再在句尾添加排序子句,一致倒罢了,不一致,结果就令人费劲了.

      2.利用 lag(),lead() 取上下n条记录取值

      例1:

select fdate 日期,total 金额,tax 税额,
lag(total,1,null) over(order by fdate) 上1条记录金额,
lead(total,1,null) over(order by fdate) 下1条记录金额,yymm
from (
select fildate fdate,to_char(fildate,yyyy-mm) yymm,sum(total) total,sum(tax) tax from stkin t
group by fildate
) order by fdate,yymm;

 

Oracle的over子函数的妙用