1

Refer here for the table

There are three columns id : integer auto increment , col_jsonb: jsonb , date: timestamp. I want to merge col_jsonb row values into json build object based on date, the required output Refer here for the output

Table:

+----+----------------+------------+
| id |   col_jsonb    |    date    |
+----+----------------+------------+
|  1 | {"Morning":10} | 2020-08-09 |
|  2 | {"Evening":20} | 2020-08-09 |
|  3 | {"Night":30}   | 2020-08-09 |
|  4 | {"Morning":20} | 2020-08-10 |
+----+----------------+------------+

Expected o/p:

+----+----------------------------------------------+------------+
| id |                  col_jsonb                   |    date    |
+----+----------------------------------------------+------------+
|  1 | [{"Morning":10},{"Evening":20},{"Night":30}] | 2020-08-09 |
|  2 | {"Morning":20}                               | 2020-08-10 |
+----+----------------------------------------------+------------+
2
  • Why does have {"Morning":20} the id 2? In the input data id 2 is associated with {"Evening":20}. Commented Aug 10, 2020 at 8:28
  • id is an auto increment column Commented Aug 10, 2020 at 8:33

1 Answer 1

2

Try This query:

select 
    row_number() over (order by date_) as "id", 
    jsonb_agg(col_jsonb), 
    date_ as "Date"
from 
    example 
group by 
    date_

row_number is added for numbering of rows if required

DEMO

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.