当两个ID在Scala中具有相同的最高价格时,使用较小的ID获得最高价格

问题描述 投票:-2回答:2

我有一个数据帧调用productPrice有列ID和价格,我想获得具有最高价格的ID,如果两个ID具有相同的最高价格,我只得到具有较小ID号的那个。我用

val highestprice = productPrice.orderBy(asc("ID")).orderBy(desc("price")).limit(1)但是我得到的结果不是具有较小ID的那个,而是我得到的那个是具有更大ID的那个。我不知道我的逻辑有什么问题,任何想法?

scala apache-spark apache-spark-sql databricks
2个回答
3
投票

试试这个。

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|
+---+-----+

0
投票

使用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)
© www.soinside.com 2019 - 2024. All rights reserved.