PostgreSQL supports arrays, but does not have a function to sort the inner elements of the data. Today I wrote one with Plpgsql and Plpythonu, respectively.
Sample Table structure:
t_girl=# \d Test_array; Table "Ytt.test_array" Column | Type | Modifiers --------+-----------+---------------------------------------------------------ID | integer | NOT null default nextval (' Test_array_id_seq ':: Regclass) str1 | Integer[] | Indexes: "Test_array_pkey" PRIMARY KEY, Btree (ID)
Sample data:
t_girl=# select * from Test_array; ID | STR1 ----+--------------------------- 1 | {100,200,300,5,10,20,100} 2 | {200,100,2,30,0,5} 3 | {2000,101,2,30,0,10} (3 rows) time:1.513 ms
plsql storage function Array_sort Execution Result:
Ascending
t_girl=# Select Id,array_sort (str1, ' ASC ') from Test_array; ID | Array_sort ----+--------------------------- 1 | {5,10,20,100,100,200,300} 2 | {0,2,5,30,100,200} 3 | {0,2,10,30,101,2000} (3 rows) time:2.377 ms
Descending
t_girl=# Select Id,array_sort (str1, ' desc ') from Test_array; ID | Array_sort ----+--------------------------- 1 | {300,200,100,100,20,10,5} 2 | {200,100,30,5,2,0}
python storage function Array_sort_python execution results:
Descending:
t_girl=# Select Id,array_sort_python (str1, ' desc ') from Test_array; ID | Array_sort_python ----+--------------------------- 1 | {300,200,100,100,20,10,5} 2 | {200,100,30,5,2,0} 3 | {2000,101,30,10,2,0} (3 rows)
time:2.797 ms
Ascending:
t_girl=# Select Id,array_sort_python (str1, ' ASC ') from Test_array; ID | Array_sort_python ----+--------------------------- 1 | {5,10,20,100,100,200,300} 2 | {0,2,5,30,100,200}
attached: Array_sort_python code:
CREATE or replace FUNCTION Array_sort_python (c1 text [],f_order text) RETURNS text [] as $ $result = []if f_order.lower () = = ' ASC ': c1.sort () result = C1elif F_order.lower () = = ' desc ': c1.sort (reverse=true) result = C1else: Passreturn result$$ LANGUAGE Plpythonu;
Array_sort Code:
Create or Replace function Array_sort (anyarray,f_order text) returns Anyarray as $ytt $declare array1 alias for $1;
tmp int; result text [];begin if lower (f_order) = ' desc ' then-for- tmp in select Unnest (array1) as a order by a desc loo P Result: = Array_append (result,tmp::text); End Loop; return result; elsif lower (F_order) = ' ASC ' then- tmp in select Unnest (array1) as a order by a ASC loop Result: = array _append (result,tmp::text); End Loop; return result; else return array[' F_order must be ASC or desc! ']; End If;end; $ytt $ language plpgsql;