简体   繁体   English

json_agg 的 PSQL 动态键值

[英]PSQL Dynamic Key value for json_agg

I have this table structure:我有这个表结构:

在此处输入图像描述

I'm grouping every element into an array based on the name column:我根据名称列将每个元素分组到一个数组中:

SELECT json_agg(json_build_object(
  'id', id,
  'time', time,
  'version', version,
  'desc1', 'desc1',
  'desc2', 'desc2',
 ))
FROM my_table
GROUP BY name

which gives me this result:这给了我这个结果:

[ { json_agg: [ [Object] ] }, { json_agg: [ [Object] ] } ]

how ever I want the json_agg key to be the same as the name column value.我如何希望json_agg键与name列值相同。 like this:像这样:

[ { test1: [ [Object] ] }, { test2: [ [Object] ] } ]

How do I achieve this?我如何实现这一目标? Using an AS name doesn't work.使用AS name不起作用。

For each grouping, you to build a new object using name and the aggregated array result in a subquery.对于每个分组,您使用name构建一个新对象,聚合数组会产生一个子查询。 Then aggregate the objects created in that subquery into a single array.然后将该子查询中创建的对象聚合到一个数组中。

SELECT
  json_agg(elem) arr
FROM

(
SELECT
    json_build_object(
      name,
      json_agg(json_build_object(
        'id', id,
        'time', time,
        'version', version,
        'desc1', 'desc1',
        'desc2', 'desc2',
      ))
    ) elem

FROM
 my_table

GROUP BY
  name
) elem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM