本文共 1845 字,大约阅读时间需要 6 分钟。
1.函数说明
RANK() 排序相同时会重复,总数不会变
DENSE_RANK() 排序相同时会重复,总数会减少
ROW_NUMBER() 会根据顺序计算
First_VALUE()取当前窗口第一个值
LAST_VALUE()取当前窗口最后一个值
2.数据准备
表6-7 数据准备
name | subject | score |
孙悟空 | 语文 | 87 |
孙悟空 | 数学 | 95 |
孙悟空 | 英语 | 68 |
大海 | 语文 | 94 |
大海 | 数学 | 56 |
大海 | 英语 | 84 |
宋宋 | 语文 | 64 |
宋宋 | 数学 | 86 |
宋宋 | 英语 | 84 |
婷婷 | 语文 | 65 |
婷婷 | 数学 | 85 |
婷婷 | 英语 | 78 |
3.需求
计算每门学科成绩排名。
4.创建本地movie.txt,导入数据
[tom@hadoop102 datas]$ vi score.txt
5.创建hive表并导入数据
create table score( name string, subject string, score int) row format delimited fields terminated by "\t"; load data local inpath '/opt/module/datas/score.txt' into table score; |
6.按需求查询数据
select name, subject, score, rank() over(partition by subject order by score desc) rp, dense_rank() over(partition by subject order by score desc) drp, row_number() over(partition by subject order by score desc) rmp from score;
name subject score rp drp rmp 孙悟空 数学 95 1 1 1 宋宋 数学 86 2 2 2 婷婷 数学 85 3 3 3 大海 数学 56 4 4 4 宋宋 英语 84 1 1 1 大海 英语 84 1 1 2 婷婷 英语 78 3 2 3 孙悟空 英语 68 4 3 4 大海 语文 94 1 1 1 孙悟空 语文 87 2 2 2 婷婷 语文 65 3 3 3 宋宋 语文 64 4 4 4 |
需求1:
// 按照科目进行排名
select * ,rank() over(partition by subject order b score desc ) rank
from score;需求二:
// 给每个学生的总分
select name,sum(score) sumScore from score group by name// 给每个学生的总分进行排名
select name,rank() over(order by sumScore desc) rank
from (select name,sum(score) sumScore from score group by name)tmp
需求三:只查询每个科目的成绩的前2名
// 只查询每个科目的成绩的前2名
select * from (select *,rank() over(partition by subject order by score desc) rank from score) tmp where rank <3需求四:查询学生成绩,并显示当前科目最高分
//查询学生成绩,并显示当前科目最高分
select *, first_value(score) over(partition by subject order by score desc) max_score, first_value(score) over(partition by subject order by score ) last_score from score // 多个开窗函数存在,且窗口的设置的排序不同,结果的打印顺序按照最后一个函数操作的结果!需求五:查询学生成绩,并显示当前科目最低分
//查询学生成绩,并显示当前科目最低分
select *, first_value(score) over(partition by subject order by score desc) max_score from score转载地址:http://hcuwi.baihongyu.com/