cookie4.txtcookie
cookie1,2015-04-10 10:00:02,url2 cookie1,2015-04-10 10:00:00,url1 cookie1,2015-04-10 10:03:04,1url3 cookie1,2015-04-10 10:50:05,url6 cookie1,2015-04-10 11:00:00,url7 cookie1,2015-04-10 10:10:00,url4 cookie1,2015-04-10 10:50:01,url5 cookie2,2015-04-10 10:00:02,url22 cookie2,2015-04-10 10:00:00,url11 cookie2,2015-04-10 10:03:04,1url33 cookie2,2015-04-10 10:50:05,url66 cookie2,2015-04-10 11:00:00,url77 cookie2,2015-04-10 10:10:00,url44 cookie2,2015-04-10 10:50:01,url55
use cookie; drop table if exists cookie4; create table cookie4(cookieid string, createtime string, url string) row format delimited fields terminated by ','; load data local inpath "/home/hadoop/cookie4.txt" into table cookie4; select * from cookie4;
LAG(col,n,DEFAULT) 用於統計窗口內往上第n行值函數
第一個參數爲列名,
第二個參數爲往上第n行(可選,默認爲1),
第三個參數爲默認值(當往上第n行爲NULL時候,取默認值,如不指定,則爲NULL)oop
select cookieid, createtime, url, row_number() over (partition by cookieid order by createtime) as rn, LAG(createtime,1,'1970-01-01 00:00:00') over (partition by cookieid order by createtime) as last_1_time, LAG(createtime,2) over (partition by cookieid order by createtime) as last_2_time from cookie.cookie4;
last_1_time: 指定了往上第1行的值,default爲'1970-01-01 00:00:00' cookie1第一行,往上1行爲NULL,所以取默認值 1970-01-01 00:00:00 cookie1第三行,往上1行值爲第二行值,2015-04-10 10:00:02 cookie1第六行,往上1行值爲第五行值,2015-04-10 10:50:01 last_2_time: 指定了往上第2行的值,爲指定默認值 cookie1第一行,往上2行爲NULL cookie1第二行,往上2行爲NULL cookie1第四行,往上2行爲第二行值,2015-04-10 10:00:02 cookie1第七行,往上2行爲第五行值,2015-04-10 10:50:01
與LAG相反url
LEAD(col,n,DEFAULT) 用於統計窗口內往下第n行值spa
第一個參數爲列名,
第二個參數爲往下第n行(可選,默認爲1),
第三個參數爲默認值(當往下第n行爲NULL時候,取默認值,如不指定,則爲NULL)code
select cookieid, createtime, url, row_number() over (partition by cookieid order by createtime) as rn, LEAD(createtime,1,'1970-01-01 00:00:00') over (partition by cookieid order by createtime) as next_1_time, LEAD(createtime,2) over (partition by cookieid order by createtime) as next_2_time from cookie.cookie4;
--邏輯與LAG同樣,只不過LAG是往上,LEAD是往下。orm
取分組內排序後,截止到當前行,第一個值blog
select cookieid, createtime, url, row_number() over (partition by cookieid order by createtime) as rn, first_value(url) over (partition by cookieid order by createtime) as first1 from cookie.cookie4;
取分組內排序後,截止到當前行,最後一個值排序
select cookieid, createtime, url, row_number() over (partition by cookieid order by createtime) as rn, last_value(url) over (partition by cookieid order by createtime) as last1 from cookie.cookie4;
select cookieid, createtime, url, row_number() over (partition by cookieid order by createtime) as rn, LAST_VALUE(url) over (partition by cookieid order by createtime) as last1, FIRST_VALUE(url) over (partition by cookieid order by createtime desc) as last2 from cookie.cookie4 order by cookieid,createtime;
提示:在使用分析函數的過程當中,要特別注意ORDER BY子句,用的不恰當,統計出的結果就不是你所指望的。hadoop