将列中的结果设置为列名称

时间:2018-04-11 10:50:38

标签: json postgresql jsonb

我有这张桌子:

-----------------------------
| cluster | nr | description|
-----------------------------
| A       | 1  | type       |
| A       | 2  | source     |
| A       | 3  | depth      |
| B       | 8  | rise       |
| B       | 12 | cause      |
-----------------------------

我想创建一个像这样的json:

 { 
    "clusters": {
        "A": [{
               "nr": 1, 
               "description": "type"
           }, {
               "nr": 2, 
               "description": "source"
           }, {
               "nr": 3, 
               "description": "depth"
        }],
        "B": [{
               "nr": 8, 
               "description": "rise"
             }, {
               "nr": 12, 
               "description": "cause"
        }]
    }
 }

因此,我试图这样做:

select row_to_json(t)
from (
    SELECT cluster, nr, description
    FROM mytable
) t


select row_to_json(t)
from (
    select array_agg(d.cluster) as cluster
    from (
        SELECT cluster, surveynr, description
        FROM events.clusterbyactivescores 
    ) d
) t

以及其他一些我忘了的事情.. 似乎都没有做到这一点。

这样做的最佳方式是什么?

提前致谢

1 个答案:

答案 0 :(得分:2)

使用jsonb类型the - operator,这样可以构建紧凑而优雅的查询:

select jsonb_build_object('clusters', jsonb_object_agg(cluster, obj))
from (
    select 
        cluster, 
        jsonb_agg(to_jsonb(t) - 'cluster') as obj
    from my_table t
    group by 1
    ) s