oracle之lead()/lag() over()分析函数
1)
SELECT userid,logintime,lead(trunc(logintime),2) over(PARTITION BY userid ORDER BY trunc(logintime)) as rn
from temp1
lead函数是按iuserid升序排序,把距离当前行的下数第二行的logintime记录显示在当前行的列rn,为null显示null,如下图:
注:若需要降序排序,在order by 后面加desc即可
2)
SELECT userid,logintime,lag(trunc(logintime), 3 - 1) over(PARTITION BY userid ORDER BY trunc(logintime)) as rn
from temp1
lag函数是按userid升序排序,把距离当前行的上数第二行的logintime记录显示在当前行的列rn,为null显示null,如下图:
3)如要查询连续三天登录的用户:
原始数据:
连续三天登录的用户:
with tt as
(
SELECT userid,logintime1,lag(logintime1,3-1) over(PARTITION BY userid ORDER BY trunc(logintime1)) as lasttime
from (
select distinct userid,trunc(logintime) logintime1 from temp1 order by userid,logintime1) t
)
select * from tt where lasttime is not null and (logintime1-lasttime)=2
本站内容来源于作者发布和网络转载,如有版权相关问题请及时与我们取得联系,我们将立即删除。