Skip to content
Advertisement

Aggregation of Json objects on a relational table on Postgres

I have a relational table that contains three variable values, an ID, and the date broken down into parts.

The goal is to aggregate that data into a JSONB/Relational Table, with the columns A, B, and C in a JSONB object: {A:5, B:10, C:15} which is the value to another JSONB object with the Day as the key.

Additionally, I want to aggregate the data so that all of the data for every month is within one object, with the final result looking like the following:

I’ve been able to get as far as creating an the data with a row for every day, but I’m getting stuck on aggregating them all by month, year, and ID.

Any help would be greatly appriciated.

Advertisement

Answer

You can use json_build_object() and json_object_agg():

Demo on DB Fiddle:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement