Based on this I have a table which has values which will be the column names of the PostgreSQL query result.
id col1 col2
----------------------
0 name ax
0 name2 bx
0 name3 cx
1 name dx
1 name2 ex
1 name2 fx
... ... ...
Now I want the result of the query to look like this
id name name2 name3 ...
0 ax bx cx ...
1 dx ex fx ...
The number of fields on col1 is changed each time that a new field is added. So for that I need to generate a function that will return the results in that way in a dynamic way.
This did that:
SELECT
id,
/* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
/* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
FROM mytable
GROUP BY id
but I need to have it dynamic because the col1 names can be a big list so I cant update the query each time that new name is added in the col1.
I checked how to do that using the pivot table, I tried to follow this example but also there the fields are well known, please can someone help me?