1. 程式人生 > 其它 >大資料之Hive:其他常用查詢函式之視窗函式

大資料之Hive:其他常用查詢函式之視窗函式

技術標籤:大資料系列二

4 視窗函式(開窗函式)
1.相關函式說明
OVER():指定分析函式工作的資料視窗大小,這個資料視窗大小可能會隨著行的變而變化。
CURRENT ROW:當前行
n PRECEDING:往前n行資料
n FOLLOWING:往後n行資料
UNBOUNDED:起點,UNBOUNDED PRECEDING 表示從前面的起點, UNBOUNDED FOLLOWING表示到後面的終點
LAG(col,n,default_val):往前第n行資料
LEAD(col,n, default_val):往後第n行資料
NTILE(n):把有序分割槽中的行分發到指定資料的組中,各個組有編號,編號從1開始,對於每一行,NTILE返回此行所屬的組的編號。注意:n必須為int型別。

2.資料準備:name,orderdate,cost

jack,2017-01-01,10
tony,2017-01-02,15
jack,2017-02-03,23
tony,2017-01-04,29
jack,2017-01-05,46
jack,2017-04-06,42
tony,2017-01-07,50
jack,2017-01-08,55
mart,2017-04-08,62
mart,2017-04-09,68
neil,2017-05-10,12
mart,2017-04-11,75
neil,2017-06-12,80
mart,2017-04-13,94

3.需求
(1)查詢在2017年4月份購買過的顧客及總人數
(2)查詢顧客的購買明細及月購買總額

(3)上述的場景, 將每個顧客的cost按照日期進行累加
(4)查詢每個顧客上次的購買時間
(5)查詢前20%時間的訂單資訊
4.建立本地business.txt,匯入資料

[[email protected] datas]$ vi business.txt

5.建立hive表並匯入資料

create table business(
name string, 
orderdate string,
cost int
) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';
load data local inpath "/opt/module/datas/business.txt"
into table business;

6.按需求查詢資料
(1)查詢在2017年4月份購買過的顧客及總人數

select name,count(*) over () 
from business 
where substring(orderdate,1,7) = '2017-04' 
group by name;

(2)查詢顧客的購買明細及月購買總額

select name,orderdate,cost,sum(cost) over(partition by month(orderdate)) from
 business;

(3)上述的場景, 將每個顧客的cost按照日期進行累加

select name,orderdate,cost,sum(cost) over(partition by name order by orderdate rows between UNBOUNDED PRECEDING and current row ) as sample4  from
 business;

(4)檢視顧客上次的購買時間

select name,orderdate,cost, 
lag(orderdate,1,'1900-01-01') over(partition by name order by orderdate ) as time1, lag(orderdate,2) over (partition by name order by orderdate) as time2 
from business;

(5)查詢前20%時間的訂單資訊

select * from (
    select name,orderdate,cost, ntile(5) over(order by orderdate) sorted
    from business
) t
where sorted = 1;