Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Spark Dataframe with two columns in different order

Let's say, I have a table like this:

A,B
2,6
1,2
1,3
1,5
2,3

I want to sort it with ascending order for column A but within that I want to sort it in descending order of column B, like this:

A,B
1,5
1,3
1,2
2,6
2,3

I have tried to use orderBy("A", desc("B")) but it gives an error.

How should I write the query using dataframe in Spark 2.0?

like image 436
kello Avatar asked Nov 27 '18 03:11

kello


1 Answers

Use Column method desc, as shown below:

val df = Seq(
  (2,6), (1,2), (1,3), (1,5), (2,3)
).toDF("A", "B")

df.orderBy($"A", $"B".desc).show
// +---+---+
// |  A|  B|
// +---+---+
// |  1|  5|
// |  1|  3|
// |  1|  2|
// |  2|  6|
// |  2|  3|
// +---+---+
like image 108
Leo C Avatar answered Sep 24 '22 04:09

Leo C