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

5
  • Remove the group by if you want one row. Commented Mar 10, 2018 at 17:12
  • Something like this? stackoverflow.com/questions/24006291/… Commented Mar 10, 2018 at 17:13
  • @GordonLinoff If I remove the group by I get the error that they must be in a GROUP BY because I'm concating them to use name and r_id as the keys of the hash. If I remove the concat and group_by I do only get one row but not as expected. Commented Mar 10, 2018 at 17:20
  • @SimonBerthiaume It's very close to the second result he is looking for but I'm not entirely sure how to make It work here. Commented Mar 10, 2018 at 17:37
  • I added a sqlfiddle sqlfiddle.com/#!17/0b10d/1 Commented Mar 10, 2018 at 17:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.