中执行此操作
我的数据框如下:
Tags Place Count
Sales New Jersey 200
Sales Hong Kong 200
Sales Florida 200
Trade New York 150
Trade San Jose 150
Trade New Jersey 150
Market New Jersey 50
Market Michigan 50
Market Denver 50
您可以看到标签已经在此表中按"计数"进行排序。我想从每个组中获得第一个n标签,其中组为"标签"
说我获得了第一个2,然后由此产生的数据框架应该是这样:
标签位置count
Sales New Jersey 200
Sales Hong Kong 200
Trade New York 150
Trade San Jose 150
Market New Jersey 50
Market Michigan 50
我该如何在Spark SQL?
以下是答案
you need to create data frame using HiveContext
import org.apache.spark.sql.hive.HiveContext
val hivecontext = new HiveContext(sc)
val df= hivecontext.createDataFrame(data,schema)
df.registerTempTable("df")
hivecontext.sql("SELECT tag,place,count FROM (SELECT tag,place,count,ROW_NUMBER() OVER (PARTITION BY tag) as rank FROM df) tmp WHERE rank <= 2 ORDER BY count DESC").show(false)
或
import org.apache.spark.sql.functions.row_number
import org.apache.spark.sql.expressions.Window
val w = Window.partitionBy(df("tag"))
val rankDesc = row_number().over(w).alias("rank")
df.select($"*", rankDesc).filter($"rank" <= 2 || $"rank" <= 2).orderBy($"count".desc).drop($"rank").show(false)
输出:
------- ------------ ----- | tag | place | count | ------- ------------ ----- |销售|香港| 200 ||销售|新泽西| 200 ||贸易|纽约| 150 ||贸易|圣何塞| 150 ||市场|新泽西州| 50 ||市场|密歇根州| 50 | ------- ------------ -----