Postgres - 在分组的JSON树中转换单个表

时间:2018-04-09 22:06:44

标签: json database postgresql

我有一张包含此数据的表格

lvl1           lvl2             lvl3         item
----           ----             ----         ----
a0             b0               c0           1
a0             b0               c1           2
a0             b0               c1           3
a0             b1               c2           4
a1             b1               c3           5
a1             b2               c0           6

如何在像这样的对象树中转换它?

[
  {
    id: 'a0', 
    children: [
      {
        id: 'b0',
        children: [
          {
            id: 'c0',
            items: [1]
          },
          {
            id: 'c1',
            items: [2, 3]
          }
        ]
      },
      {
        id: 'b1',
        children: [
          {
            id: 'c2',
            items: [4]
          }
        ]
      }
    ]
  },
  {
    id: 'a1', 
    children: [
      {
        id: 'b1',
        children: [
          {
            id: 'c3',
            items: [5]
          }
        ]
      },
      {
        id: 'b2',
        children: [
          {
            id: 'c0',
            items: [6]
          }
        ]
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:1)

从某种意义上说,查询的结构类似于结果:

select json_agg(children)
from (
    select 
        json_build_object(
            'id', lvl1, 
            'children', json_agg(children order by lvl1)) as children
    from (
        select 
            lvl1, 
            json_build_object(
                'id', lvl2, 
                'children', json_agg(items order by lvl2)) as children
        from (
            select 
                lvl1, 
                lvl2, 
                json_build_object(
                    'id', lvl3, 
                    'items', json_agg(item order by lvl3)) as items
            from my_table
            group by lvl1, lvl2, lvl3
            ) s
        group by lvl1, lvl2
        ) s
    group by lvl1
    ) s;

DbFiddle.

注意,聚合中的order by不是必需的,因为json数组的顺序是未定义的。我已添加它们以获得完全预期的结果。