如何使用array_agg(order by)进行投影?

问题描述 投票:2回答:1

我有一个有三列的表:idnameposition。我想创建一个JSON数组,如下所示:

[
    {"id": 443, "name": "first"},
    {"id": 645, "name": "second"}
]

这应该由position列列出。

我从以下查询开始:

with output as
(
    select id, name
    from   the_table
)
select array_to_json(array_agg(output))
from   output

这很有用。现在我想添加订单。我从这开始:

with output as
(
    select id, name, position
    from   the_table
)
select array_to_json(array_agg(output order by output.position))
from   output

现在输出如下:

[
    {"id": 443, "name": "first", "position": 1},
    {"id": 645, "name": "second", "position": 2}
]

但我不希望输出中的position字段。

我正面临一个鸡蛋问题:我需要position列才能对它进行排序,但我也不想要position列,因为我不希望它在结果输出中。

我怎样才能解决这个问题?

我不认为以下查询是正确的,因为表格排序(理论上)在查询之间不保留:

with output as
(
    select   id, name
    from     the_table
    order by position
)
select array_to_json(array_agg(output))
from   output
postgresql
1个回答
1
投票

有两种方式(至少):

构建JSON对象:

with t(x,y) as (values(1,1),(2,2))
select json_agg(json_build_object('x',t.x) order by t.y) from t;

或删除不必要的密钥:

with t(x,y) as (values(1,1),(2,2))
select json_agg((to_jsonb(t)-'y')::json order by t.y) from t;

请注意,在第二种情况下,您需要一些类型转换,因为-运算符仅为JSONB类型定义。

另请注意,我使用直接JSON聚合json_agg()而不是对array_to_json(array_agg())

© www.soinside.com 2019 - 2024. All rights reserved.