array_sort:数组排序
速查结论
array_sort(expr, func) 是 Spark SQL 中用于对数组元素进行排序的函数。
语法
array_sort(expr [, func])
参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
| expr | ARRAY | 要排序的输入数组,元素必须是可排序的 |
| func | LAMBDA(可选) | 比较器函数,接受两个参数,返回负整数(小于)、0(等于)或正整数(大于)。如果省略,默认按升序排序 |
返回值
返回排序后的数组。对于 DOUBLE/FLOAT 类型,NaN 大于任何非 NaN 元素。null 元素将被放置在返回数组的末尾。如果比较器函数返回 null,则函数将失败并引发错误。
示例
> SELECT array_sort(array(5, 6, 1), (left, right) -> case when left < right then -1 when left > right then 1 else 0 end);
[1,5,6]
> SELECT array_sort(array('bc', 'ab', 'dc'), (left, right) -> case when left is null and right is null then 0 when left is null then -1 when right is null then 1 when left < right then 1 when left > right then -1 else 0 end);
["dc","bc","ab"]
> SELECT array_sort(array('b', 'd', null, 'c', 'a'));
["a","b","c","d",null]
常见报错与避坑指南
- null 元素排序位置:null 元素始终被放置在排序结果的末尾,无论升序还是降序。如果需要对 null 值进行自定义处理,请使用比较器函数显式定义 null 的比较逻辑。
- 比较器返回 null 会报错:自定义比较器函数不得返回 null,否则函数将抛出异常。务必在比较器中对 null 输入情况做好防御性处理。
- 排序稳定性:
array_sort不保证排序的稳定性(即相同元素的相对顺序可能发生变化)。如果需要稳定排序,请结合索引信息使用自定义比较器。
Since: 2.4.0
📱关注公众号
「数据仓库技术」文章同步更新,不错过每一篇干货

💬加群交流
备注「数据仓库技术」加入社群,每日一道大厂SQL真题
