语法:row_number() OVER(PARTITION BY …)
分组取最大的objid那一条,根据objid倒叙排序,取rn=1
select * from (select a.* ,row_number()over(partiotion by col1,col2 order by col1,col2) r from tablename ) where r=1;
分析函数和聚合函数的不同之处是什么?
普通的聚合函数用group by分组,每个分组返回一个统计值,而分析函数采用partition by分组,并且每组每行都可以返回一个统计值。
分析函数的形式
分析函数带有一个开窗函数over(),包含三个分析子句:分组(partition by), 排序(order by), 窗口(rows) ,他们的使用形式如下:over(partition by xxx order by yyy rows between zzz)
–利用开窗函数取每组数据的最后一条数据
SQL>select * from (select ROW_NUMBER() over (partition by accountid order by updatetimestamp desc) rn, plm_openaccountrecon.* from plm_openaccountrecon) where rn = 1 and t.accountid = :accountid
–unbounded preceding and unbouned following针对当前所有记录的前一条、后一条记录,也就是表中的所有记录
–unbounded:不受控制的,无限的
–preceding:在…之前
–following:在…之后
–第一行到当前行
SQL> select t.objid, t.applyempid, t.applydate, t.status, t.leavetype, t.leavedays, SUM(leavedays) OVER(PARTITION BY applyempid ORDER BY objid ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) lds from RT_GTCXLEAVE t;
–当前行至最后一行
SQL> select t.objid, t.applyempid, t.applydate, t.status, t.leavetype, t.leavedays, SUM(leavedays) OVER(PARTITION BY applyempid ORDER BY objid ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) lds from RT_GTCXLEAVE t;
–当前行的上一行 (rownum – 1) 到当前行
–BETWEEN 1 PRECEDING AND CURRENT ROW
SQL> select t.objid, t.applyempid, t.applydate, t.status, t.leavetype, t.leavedays, SUM(leavedays) OVER(PARTITION BY applyempid ORDER BY objid ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) lds from RT_GTCXLEAVE t;
–当前行的上一行 (rownum – 1) 到当前行的下两行 (rownum + 2)
–ROWS BETWEEN 1 PRECEDING AND 2 FOLLOWING