相关疑难解决方法(0)

从JSONB字段中展平聚合的键/值对?

我在Postgres 9.4中使用下表:

     Column      ?         Type         ? Modifiers
???????????????????????????????????????????????????????????????
 id              ? integer              ? not null default
 practice_id     ? character varying(6) ? not null
 date            ? date                 ? not null
 pct_id          ? character varying(3) ?
 total_list_size ? double precision     ? not null
 star_pu         ? jsonb                ?
Run Code Online (Sandbox Code Playgroud)

我有以下查询:

SELECT date,
       AVG(total_list_size) AS total_list_size,
       json_object_agg(key, val) AS star_pu
FROM (SELECT date,
             SUM(total_list_size) AS total_list_size,
             key, SUM(value::numeric) val FROM frontend_practicelist p,
             jsonb_each_text(star_pu)
       GROUP BY date, key ) p
GROUP BY date
ORDER BY date;
Run Code Online (Sandbox Code Playgroud)

它给我一个附加到JSON对象的结果 …

postgresql json jsonb postgresql-9.4

12
推荐指数
1
解决办法
4428
查看次数

如何控制 jsonb_object_agg 中字段的顺序

我正在尝试构建一个 jsonb 对象,其键按字母顺序排列。然而,它似乎jsonb_object_agg(k, v)忽略了输入的顺序,并按密钥长度对输入进行排序,然后按字母顺序排序。

例如

select jsonb_object_agg(k, v order by k) from (
    values ('b', 'b_something'), ('ab', 'ab_something')
) as t (k,v)
Run Code Online (Sandbox Code Playgroud)

给出

{
  "b": "b_something",
  "ab": "ab_something"
}
Run Code Online (Sandbox Code Playgroud)

但我需要的是

{
  "ab": "ab_something"
  "b": "b_something",
}
Run Code Online (Sandbox Code Playgroud)

有办法实现这一点吗?

上下文 我正在展平一个 json 列,其中的内容遵循统一但笨重的模式。由于这个有用的答案,我已经成功地做到了这一点,但是按键的顺序并不是我需要它们的方式。

postgresql aggregate-functions postgresql-10

3
推荐指数
1
解决办法
2972
查看次数