Skip to content
Advertisement

POSTGRESQL: Group the values as ARRAY of ARRAYS

Below is my input table of data

Input :

I need the values to be sorted as an ARRAY values of Quarters [Q1,Q2,Q3,Q4] for each system name and under each Quarter it should have the array values of the Years [Y1,Y2]
Value 1 : {{“AB”,”XX”},{“EF”,”ZZ”},{“IJ”,”NN”},{“MN”,”TT”}}
Value 2 : {{“CD”,”YY”},{“GH”,”MM”},{“KL”,”KK”},{“OP”,”QQ”}}

The expected output is something like this :

Output :

I have tried using ARRAY_AGG function order by Quarter.

Advertisement

Answer

Use ARRAY_AGG, and perform a two-level aggregation. First, aggregation by system and quarter to generate a series of records containing arrays for each quarter. Then, aggregate a second time by system alone to generate a single array-of-arrays.

enter image description here

Demo

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