天天看點

Spark 開窗函數

row_number() 開窗函數是按照某個字段分組,然後取另一字段的前幾個的值,相當于 分組取topN

如果SQL語句裡面使用到了開窗函數,那麼這個SQL語句必須使用HiveContext來執行,HiveContext預設情況下在本地無法建立。在MySql8之後也增加了開窗函數。

開窗函數格式:

val spark = SparkSession.builder()
      .appName("window")
      .enableHiveSupport()
      .getOrCreate()
    spark.sql("use spark")//使用spark庫
    //建立sales表
    spark.sql("create table if not exists sales(date String,type String,price Int) row format delimited fields terminated by '\t'")
    //加載本地資料到sales表中
    spark.sql("load data local inpath '/root/sales' into table sales")
    //按照type分組,按照價格排序
val result = spark.sql("select date,type,price from (select date,type,price,row_number() over (partition by type order by price desc) rank from sales) t where t.rank<=3")
    result.write.mode(SaveMode.Append).saveAsTable("salesResult")
    result.show(100)
           

繼續閱讀