1

This is what I have right now

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);

What this returns is 3 rows of data, I need them in the same row as a hash

Got:

row1: {"Name1" : [["70.2", "2018-02-19T16:26:08.857134"], ["69.93", "2018-02-19T16:26:16.568789"]}

row2: {"Name2" : [["70.2", "2018-02-19T16:26:08.857134"], ["69.93", "2018-02-19T16:26:16.568789"]}

row3: {"NewName1" : [["70.2", "2018-02-19T16:26:08.857134"], ["69.93", "2018-02-19T16:26:16.568789"]}

Expected

{
    "Name1": [
        ["70.2", "2018-02-19T16:26:08.857134"],
        ["69.93", "2018-02-19T16:26:16.568789"]
    ],
    "Name2": [
        ["70.2", "2018-02-19T16:26:08.857134"],
        ["69.93", "2018-02-19T16:26:16.568789"]
    ],
    "NewName1": [
        ["70.2", "2018-02-19T16:26:08.857134"],
        ["69.93", "2018-02-19T16:26:16.568789"]
    ]
}

Here is a sqlfiddle with this example http://sqlfiddle.com/#!17/0b10d/1

acrogenesis
  • 937
  • 9
  • 21

1 Answers1

1

Use the aggregate function json_object_agg():

select json_object_agg(name, details)
from (
    select concat(name, r_id) as name, 
           json_agg(json_build_array(value,created_at) order by created_at asc) as details
    from data
    group by concat(name, r_id)
    ) s

SqlFiddle.

klin
  • 112,967
  • 15
  • 204
  • 232