我有一个数据帧调用productPrice有列ID和价格,我想获得具有最高价格的ID,如果两个ID具有相同的最高价格,我只得到具有较小ID号的那个。我用
val highestprice = productPrice.orderBy(asc("ID")).orderBy(desc("price")).limit(1)
但是我得到的结果不是具有较小ID的那个,而是我得到的那个是具有更大ID的那个。我不知道我的逻辑有什么问题,任何想法?
试试这个。
scala> val df = Seq((4, 30),(2,50),(3,10),(5,30),(1,50),(6,25)).toDF("id","price")
df: org.apache.spark.sql.DataFrame = [id: int, price: int]
scala> df.show
+---+-----+
| id|price|
+---+-----+
| 4| 30|
| 2| 50|
| 3| 10|
| 5| 30|
| 1| 50|
| 6| 25|
+---+-----+
scala> df.sort(desc("price"), asc("id")).show
+---+-----+
| id|price|
+---+-----+
| 1| 50|
| 2| 50|
| 4| 30|
| 5| 30|
| 6| 25|
| 3| 10|
+---+-----+
使用Spark SQL解决相同的问题:
val df = Seq((4, 30),(2,50),(3,10),(5,30),(1,50),(6,25)).toDF("id","price")
df.createOrReplaceTempView("prices")
--
%sql
SELECT id, price
FROM prices
ORDER BY price DESC, id ASC
LIMIT(1)