前言
对于字符串数值的排序底层是按照ASCII码规则进行排序的,说的简单点就是在对字符串类型的数字值排序时优先排第一位,然后第一位有相同的比较第二位,多位数以此类推。,因此一定要先将字符串转为Int(或double等)在进行排序
Spark案例
准备数据
1
2
3
4
5
6
7
8
9
10
11
代码
object SortTest {
def main(args: Array[String]): Unit = {
val spark = SparkSession
.builder()
.appName("test")
.master("local[*]")
.getOrCreate()
import spark.implicits._
val df_age = spark.read.
textFile("./data/age")
.toDF("age")
df_age.orderBy($"age".desc).show()
spark.stop()
}
}
结果
+---+
|age|
+---+
| 9|
| 8|
| 7|
| 6|
| 5|
| 4|
| 3|
| 2|
| 11|
| 10|
| 1|
+---+
转换为Int
object SortTest {
def main(args: Array[String]): Unit = {
val spark = SparkSession
.builder()
.appName("test")
.master("local[*]")
.getOrCreate()
import spark.implicits._
val df_age = spark.read.
textFile("./data/age")
.toDF("age")
df_age.select(df_age("age").cast("int"))
.orderBy($"age".desc).show()
spark.stop()
}
}
结果
+---+
|age|
+---+
| 11|
| 10|
| 9|
| 8|
| 7|
| 6|
| 5|
| 4|
| 3|
| 2|
| 1|
+---+
Hive案例
创建Hive表
CREATE TABLE order_test(id STRING,text STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';
准备数据
1,a
2,b
3,c
4,d
5,e
6,f
7,g
8,h
9,i
10,j
11,k
加载数据
load data inpath '/test/order.txt' into table order_test;
执行Hive
select * from order_test order by id desc;
结果
9 i
8 h
7 g
6 f
5 e
4 d
3 c
2 b
11 k
10 j
1 a
转换为Int
select cast(order_test as int) as c from order_test order by c desc;
结果
11
10
9
8
7
6
5
4
3
2
1
后记
对字符串数值的排序一定要记得转为Int