问题
Suppose you need to sort an array of numranges
by, say, descending left boundary. Is the following approach the simplest: unnest
the array into a table, sort the table, array_agg
it back into an array. How would that look in code? Here is my non-working attempt:
DO $$
DECLARE
x numrange[] := '{"[0, 3]", "[0, 1]", "[3, 5]", "[3, 8]"}';
BEGIN
x := (
WITH x AS (
SELECT xrow FROM unnest(x) AS xrow
)
SELECT array_agg(xrow) FROM x ORDER BY lower(xrow) DESC
);
RAISE NOTICE '%', x;
END;
$$;
回答1:
You must move ORDER BY
into aggregate function, to afect aggragate order see manual:
DO $$
DECLARE
x numrange[] := '{"[0, 3]", "[0, 1]", "[3, 5]", "[3, 8]"}';
BEGIN
x := (WITH x AS (
SELECT xrow FROM unnest(x) AS xrow
)
SELECT array_agg(xrow ORDER BY lower(xrow) DESC) FROM x
);
RAISE NOTICE '%', x;
END;
$$;
来源:https://stackoverflow.com/questions/33954733/postgresql-sort-an-array-of-elements-using-some-sorting-condition