所以我有一个名为data
的表,它有4列名称(字符串),值(字符串),created_at(时间戳),r_id(int8),我正在尝试获取一个JSON对象,它给了我所有值按名称和r_id的concat分组。我所取得的最接近的成绩如下:
SELECT json_build_object(concat(name, r_id), json_build_array("data".value,created_at))
FROM data
给出:
{"Name1" : ["69.39", "2018-02-19T16:27:17.482111"]}
{"Name1" : ["69.66", "2018-02-19T16:26:21.075247"]}
{"Name1" : ["69.93", "2018-02-19T16:26:28.809292"]}
{"NewName1" : ["25.75", "2018-02-19T16:27:29.024595"]}
...
预期:
{"Name1" : [["69.39", "2018-02-19T16:27:17.482111"],["69.66", "2018-02-19T16:26:21.075247"],["69.93", "2018-02-19T16:26:28.809292"]]}
{"NewName1" : [["25.75", "2018-02-19T16:27:29.024595"]]}
...
答案 0 :(得分:1)
您可以使用json_agg
聚合数组:
SELECT json_build_object(concat(name, r_id), json_agg(json_build_array("data".value,created_at)))
FROM data group by concat(name, r_id)
当然,如果您需要订购,可以添加订单:
SELECT json_build_object(concat(name, r_id), json_agg(json_build_array(value,created_at) ORDER BY created_at ASC))
FROM data
group by concat(name, r_id)