spark 窗口函数对多列数据进行排名示例

如果我们要select 同学的 id,语文成绩,语文成绩排名,数学成绩,数学成绩排名,英语成绩,英语成绩排名。
可以使用以窗口函数

## 创建表
create table t_window(id string, chinese int, math int, english int);

## 插入数据
insert into t_window 
values
('1', 99, 88, 77),
('2', 77, 99, 88), 
('3', 88, 77, 99);

## 检索数据, 最后的结果按学号排序
select id, 
chinese, row_number() over(order by chinese desc) as chinese_order,
math, row_number() over(order by math desc) as math_order ,
english, row_number() over(order by english desc) as english_order  from t_window order by id;

结果如下,

学号语文成绩语文成绩排名数学数学成绩排名英语英语成绩排名
1991882773
2773991882
3882773991

生成执行计划

== Physical Plan ==
*(4) Sort [id#156 ASC NULLS FIRST], true, 0
+- *(4) Project [id#156, chinese#157, chinese_order#145, math#158, math_order#146, english#159, english_order#147]
   +- Window [row_number() windowspecdefinition(english#159 DESC NULLS LAST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS english_order#147], [english#159 DESC NULLS LAST]
      +- *(3) Sort [english#159 DESC NULLS LAST], false, 0
         +- Window [row_number() windowspecdefinition(math#158 DESC NULLS LAST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS math_order#146], [math#158 DESC NULLS LAST]
            +- *(2) Sort [math#158 DESC NULLS LAST], false, 0
               +- Window [row_number() windowspecdefinition(chinese#157 DESC NULLS LAST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS chinese_order#145], [chinese#157 DESC NULLS LAST]
                  +- *(1) Sort [chinese#157 DESC NULLS LAST], false, 0
                     +- Exchange SinglePartition, ENSURE_REQUIREMENTS, [id=#306]
                        +- Scan hive hzz.t_window [id#156, chinese#157, math#158, english#159], HiveTableRelation [`hzz`.`t_window`, org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, Data Cols: [id#156, chinese#157, math#158, english#159], Partition Cols: []]

最终的执行计划:
先scan hzz.t_window。
Exchange SinglePartition 是把所有数据都放到一个分区,因为要全排序,没有partition by。
(1) Sort [chinese#157 DESC NULLS LAST] :对语文进行倒排序。
Window [row_number() windowspecdefinition(chinese#157…: 生成语文的顺序
(2) Sort [math#158 DESC NULLS LAST] : 对数学进行倒排序。
Window [row_number() windowspecdefinition(math#158 :生成数学的顺序
Sort [english#159 DESC NULLS LAST]:对英语进行倒排序。
Window [row_number() windowspecdefinition(english#159 :生成英语的顺序
Project 选择出需要的列。
Sort [id#156 ASC NULLS FIRST]: 对结果按学号进行全局排序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值