Spark SQL:深入理解窗口函数的使用方法
最编程
2024-07-23 07:09:56
...
package com.kfk.spark.sql
import com.kfk.spark.common.{Comm, CommSparkSessionScala}
/**
* @author : 蔡政洁
* @email :caizhengjie888@icloud.com
* @date : 2020/12/8
* @time : 12:22 下午
*/
object WindowFunctionScala {
def main(args: Array[String]): Unit = {
val spark = CommSparkSessionScala.getSparkSession()
val userPath = Comm.fileDirPath + "users.json"
spark.read.json(userPath).show()
/**
* +--------+-------+------+
* |deptName| name|salary|
* +--------+-------+------+
* | dept-1|Michael| 3000|
* | dept-2| Andy| 5000|
* | dept-1| Alex| 4500|
* | dept-2| Justin| 6700|
* | dept-2| Cherry| 3400|
* | dept-1| Jack| 5500|
* | dept-2| Jone| 12000|
* | dept-1| Lucy| 8000|
* | dept-2| LiLi| 7600|
* | dept-2| Pony| 4200|
* +--------+-------+------+
*/
spark.read.json(userPath).createOrReplaceTempView("user")
// 实现开窗函数:所谓开窗函数就是分组求TopN
spark.sql("select deptName,name,salary,rank from" +
"(select deptName,name,salary,row_number() OVER (PARTITION BY deptName order by salary desc) rank from user) tempUser " +
"where rank <=2").show()
/**
* +--------+----+------+----+
* |deptName|name|salary|rank|
* +--------+----+------+----+
* | dept-1|Lucy| 8000| 1|
* | dept-1|Jack| 5500| 2|
* | dept-2|Jone| 12000| 1|
* | dept-2|LiLi| 7600| 2|
* +--------+----+------+----+
*/
// 实现分组排序
spark.sql("select * from user order by deptName,salary desc").show()
/**
* +--------+-------+------+
* |deptName| name|salary|
* +--------+-------+------+
* | dept-1| Lucy| 8000|
* | dept-1| Jack| 5500|
* | dept-1| Alex| 4500|
* | dept-1|Michael| 3000|
* | dept-2| Jone| 12000|
* | dept-2| LiLi| 7600|
* | dept-2| Justin| 6700|
* | dept-2| Andy| 5000|
* | dept-2| Pony| 4200|
* | dept-2| Cherry| 3400|
* +--------+-------+------+
*/
}
}
推荐阅读
-
转换你的数据:深入理解 SQL Server 中的 CONVERT 函数
-
玩转数据:理解与应用SQL中的窗口函数
-
使用 Spark SQL 的窗口函数详解
-
理解并掌握Hive SQL中的窗口函数操作
-
用简单易懂的方式理解Spark SQL中的窗口函数
-
彻底理解SQL中的窗口函数(Window Functions)
-
玩转 SQL 窗口函数 (Window Function):OVER 的关键作用与应用指南" - 分组小能手:理解 PARTITION BY,就像在数据分块后为每个组执行聚合操作,不同窗口函数的分组互不影响 - 排序达人:在 OVER 之后加入 ORDER BY,就像 SQL 中一样轻松设定行的排序顺序 - 计算范围说明:引入 ROWS 子句,就像给窗口函数设置边界条件,无论是从哪一行开始计算,到哪一行结束,都能精准控制,例如要求前5行和后5行的总和,只需用 ROWS BETWEEN...AND... 指定界限规则即可。
-
深入理解Hive的窗口函数高级应用
-
理解与运用:SQL中的窗口函数详解
-
理解 SQL 窗口函数: over()与 sum, AVG, MIN, MAX 的实战应用