json_agg Postgres中的两列

时间:2017-04-17 14:44:48

标签: arrays json postgresql aggregate-functions

我有一个表,其中包含以下两列,如下所示:

rev | level
-----------
B   | 1001
B   | 1002
B   | 1003
C   | 1004
C   | 1005
D   | 1006

我正在尝试返回一个如下所示的列:

{"B":["1001","1002","1003"], "C":["1002","1003"], "D":["1006"]}

我能得到的最好的就是使用这个查询:

SELECT d.rev,
       to_json(ARRAY(SELECT level
                     FROM details
                     WHERE rev = d.rev
                     GROUP BY level
                     ORDER BY level DESC
                    )) AS level
FROM details d
GROUP BY d.rev
ORDER BY d.rev DESC

这给了我以下几行:

____________________________________
|  B    | ["1001","1002","1003"]   |
|  C    | ["1004","1005"]          |
|  D    | ["1006"]                 |
|__________________________________|

如何将这些列合并为一个JSON对象?

1 个答案:

答案 0 :(得分:6)

您可以在查询中使用json_agg()

select rev, json_agg(level) levels
from details
group by 1
order by 1;

 rev |       levels       
-----+--------------------
 B   | [1001, 1002, 1003]
 C   | [1004, 1005]
 D   | [1006]
(3 rows)

json_object_agg()将结果聚合到一个json:

select json_object_agg(rev, levels order by rev)
from (
    select rev, json_agg(level) levels
    from details
    group by 1
    ) s;

                        json_object_agg                         
----------------------------------------------------------------
 { "B" : [1001, 1002, 1003], "C" : [1004, 1005], "D" : [1006] }
(1 row)