Hive 開窗函式 cume dist

2021-10-10 11:45:45 字數 2144 閱讀 4341

題目:  獲取每個班級中,以數學成績排序,取後20%(成績從低到高)的學生資訊

(1)準備工作

資料:studentid,classid ,course, score

001,001,math,15

001,002,math,20

001,003,math,35

001,004,math,40

001,005,math,48

001,006,math,60

001,007,math,69

001,008,math,80

001,009,math,89

001,010,math,100

001,001,english,99

001,002,english,100

001,003,english,87

001,004,english,10

001,005,english,50

001,006,english,30

001,007,english,58

001,008,english,68

001,009,english,78

001,010,english,89

002,001,math,15

002,002,math,20

002,003,math,35

002,004,math,40

002,005,math,48

002,006,math,60

002,007,math,69

002,008,math,80

002,009,math,89

002,010,math,100

002,001,english,99

002,002,english,100

002,003,english,87

002,004,english,10

002,005,english,50

002,006,english,30

002,007,english,58

002,008,english,68

002,009,english,78

002,010,english,89

建表:

create table student(

classid int,

stuid int,

course string,

score int)

row format delimited fields terminated by ','

lines terminated by '\n'

stored as textfile;

上傳資料:

(2).查詢

方法一: cume_dist,分割槽後,對字段值按百分比劃分,最準確

select studentid,classid,course,score,percent_part 

from ( select studentid,classid,course,score,cume_dist() over (partition by

classid order by score) as percent_part from student where course = 'math' )tmp

where tmp.percent_part > 0.8 ;

結果:

方法二: ntile分桶/分箱,分成5個桶,但是會存在最後乙個或多個桶為空的情況,不夠精確

select studentid,classid,course,score 

from ( select studentid,classid,course,score,ntile(5) over (partition by classid order by score) as bucket from student where course = 'math' ) tmp

where tmp.bucket = 5;

Hive 開窗函式

普通聚合函式聚合的行集是組,開窗函式聚合的行集是視窗。因此,普通聚合函式每組 group by 只有乙個返回值,而開窗函式則可以為視窗中的每行都返回乙個值。分析函式 如 sum max row number 視窗子句 over函式 over partition by column n order b...

Hive開窗函式

show functions desc function extended upper current row 當前行 n preceding 向前取第n行 n following 向後取第n行 unbounded preceding 首行 unbounded following 尾行 order ...

hive開窗函式總結

1,sum 函式 注 沒有order by,不僅分區內沒有排序,sum 計算的pv也是整個分割槽的pv。max 函式無論有沒有order by 都是計算整個分割槽的最大值 2,ntile 函式 ntile n 用於將分組資料按照順序切分成n片,返回當前切片值 注 如果切片不均勻,預設增加第乙個切片的...