0

I have a field 'item_json' in item table and json like this below.

{
  "MPA0000004":{
    "2020-21":{
      "Q1":"100",
      "Q2":"25",
      "Q3":"",
      "Q4":""
    },
    "2021-22":{
      "Q1":"5",
      "Q2":"",
      "Q3":"",
      "Q4":""
    }
  },
  "MPA0000006":{
    "2020-21":{
      "Q1":"",
      "Q2":"2",
      "Q3":"",
      "Q4":"4"
    },
    "2021-22":{
      "Q1":"",
      "Q2":"6",
      "Q3":"",
      "Q4":"8"
    }
  },
  "MPA0000007":{
    "2020-21":{
      "Q1":"",
      "Q2":"",
      "Q3":"3",
      "Q4":""
    },
    "2021-22":{
      "Q1":"",
      "Q2":"",
      "Q3":"7",
      "Q4":""
    }
  }
}

Need data like this :

ITEM_ID | YEAR | Q1 | Q2 |Q3 | Q4

1 Answer 1

1

You need to unnest the nested value twice so that you can extract the quarters by year:

select i.item_id,  
       y.year,
       y.numbers ->> 'Q1' as q1,
       y.numbers ->> 'Q2' as q2,
       y.numbers ->> 'Q3' as q3,
       y.numbers ->> 'Q4' as q4
from data d
  cross join jsonb_each(d.item_json) as i(item_id, item)
  cross join jsonb_each (i.item) as y(year, numbers)
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.