度量快速开发平台-专业、快速的软件定制快开平台

标题: Oracle的over子函数的妙用 [打印本页]

作者: fteair    时间: 2020-3-20 15:54
标题: Oracle的over子函数的妙用
本帖最后由 fteair 于 2017-4-20 15:55 编辑

      例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) 本月累计税额,yymmfrom (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) 月占比,yymmfrom (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条记录金额,yymmfrom (select fildate fdate,to_char(fildate,'yyyy-mm') yymm,sum(total) total,sum(tax) tax from stkin tgroup by fildate) order by fdate,yymm;


作者: 张兴康    时间: 2020-3-20 17:03

作者: fteair    时间: 2020-3-21 17:16





欢迎光临 度量快速开发平台-专业、快速的软件定制快开平台 (http://bbs.delit.cn/) Powered by Discuz! X3.2