PostgreSQL:使用一些排序条件对元素数组进行排序

时间:2015-11-27 09:55:56

标签: arrays postgresql sorting sql-order-by aggregate-functions

假设您需要按照左下边界的下降对numranges数组进行排序。以下方法是最简单的:unnest将数组放入表中,对表进行排序,array_agg将其重新放入数组中。怎么看代码?这是我的非工作尝试:

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 个答案:

答案 0 :(得分:3)

您必须将ORDER BY移动到聚合函数中,以完成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;
$$;