2015-11-27 88 views
2

假設您需要通過降序左邊界來排序numranges的數組。以下方法最簡單:將unnest的數組放入表中,將表排序,將其array_agg它重新放回數組中。這會怎樣看代碼?這裏是我的非工作的嘗試:PostgreSQL:使用一些排序條件對元素數組進行排序

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; 
$$; 

回答

3

你必須移動到ORDER BY聚合函數,以afect aggragate爲了看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; 
$$;