数组元素排序 [英] Sorting array elements
本文介绍了数组元素排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个存储过程,将一个数组作为输入参数,并对数组进行排序并返回排序后的数组。
I want to write a stored procedure that gets an array as input parameter and sort that array and return the sorted array.
请帮助。
推荐答案
对整数数组进行排序的最佳方法无疑是使用intarray扩展,它的执行速度比任何SQL公式都要快得多:
The best way to sort an array of integers is without a doubt to use the intarray extension, which will do it much, much, much faster than any SQL formulation:
CREATE EXTENSION intarray;
SELECT sort( ARRAY[4,3,2,1] );
适用于任何数组类型的函数是:
A function that works for any array type is:
CREATE OR REPLACE FUNCTION array_sort (ANYARRAY)
RETURNS ANYARRAY LANGUAGE SQL
AS $$
SELECT ARRAY(SELECT unnest($1) ORDER BY 1)
$$;
(我用 Pavel的速度稍快(在其他地方进行了讨论)。
(I've replaced my version with Pavel's slightly faster one after discussion elsewhere).
这篇关于数组元素排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文