如何对使用json聚合的子查询的结果进行排序?

如果我有这样的架构:

CREATE TABLE plans( id integer NOT NULL, name character varying(255));
CREATE TABLE plan_items ( id integer NOT NULL, plan_id integer NOT NULL, expected_at date, status integer);

我正在通过子查询在json列上聚合plan_items结果。
像这样:
SELECT
  plans.id,
  plans.name,
  jsonb_agg((SELECT pi_cols FROM
       (SELECT plan_items.id, plan_items.expected_at, plan_items.status) pi_cols
      )) AS plan_items_data
FROM
  plans
  INNER JOIN plan_items ON plan_items.plan_id = plans.id
GROUP BY
  plans.id,
  plans.name
ORDER BY plans.id;

JSON聚合按预期工作,并为我提供了所需的结果。好的。
但我无法订购结果。

我试过了:
  jsonb_agg((SELECT pi_cols FROM
       (SELECT plan_items.id, plan_items.expected_at, plan_items.status ORDER BY plan_items.expected_at) pi_cols
      )) AS plan_items_data

并且:
  jsonb_agg((SELECT pi_cols FROM
       (SELECT plan_items.id, plan_items.expected_at, plan_items.status) pi_cols ORDER BY pi_cols.expected_at
      )) AS plan_items_data

但是这些都没有解决。

有任何想法吗?

最佳答案

正如Abelisto建议的那样,只需使用一个简单的aggregate expression with ordering即可:

jsonb_agg(plan_items ORDER BY plan_items.expected_at) AS plan_items_data

关于json - PostgreSQL jsonb_agg子查询排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40652871/

10-17 03:06