0

I have the following data in a postgres table,

enter image description here

where data is a jsonb column. I would like to get result as

[
 {field_type: "Design", briefings_count: 1, meetings_count: 13}, 
 {field_type: "Engineering", briefings_count: 1, meetings_count: 13}, 
 {field_type: "Data Science", briefings_count: 0, meetings_count: 3}
]

2 Answers 2

2

Explanation

Use jsonb_each_text function to extract data from jsonb column named data. Then aggregate rows by using GROUP BY to get one row for each distinct field_type. For each aggregation we also need to include meetings and briefings count which is done by selecting maximum value with case statement so that you can create two separate columns for different counts. On top of that apply coalesce function to return 0 instead of NULL if some information is missing - in your example it would be briefings for Data Science.

At a higher level of statement now that we have the results as a table with fields we need to build a jsonb object and aggregate them all to one row. For that we're using jsonb_build_object to which we are passing pairs that consist of: name of the field + value. That brings us with 3 rows of data with each row having a separate jsonb column with the data. Since we want only one row (an aggregated json) in the output we need to apply jsonb_agg on top of that. This brings us the result that you're looking for.

Code

Check LIVE DEMO to see how it works.

select
  jsonb_agg(
    jsonb_build_object('field_type', field_type,
                     'briefings_count', briefings_count,
                     'meetings_count', meetings_count
                     )
    ) as agg_data
from (
  select
      j.k as field_type
    , coalesce(max(case when t.count_type = 'briefings_count' then j.v::int end),0) as briefings_count
    , coalesce(max(case when t.count_type = 'meetings_count'  then j.v::int end),0) as meetings_count
  from tbl t, 
       jsonb_each_text(data) j(k,v)
  group by j.k
  ) t
Sign up to request clarification or add additional context in comments.

Comments

0

You can aggregate columns like this and then insert data to another table

select array_agg(data)
from the_table

Or use one of built-in json function to create new json array. For example jsonb_agg(expression)

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.