0

I have a table "emails":

I need this result:

the number of columns could expand in future. In fact, in the real database, I have ids with 10 emails already.

Every id, email pair is unique in the table.

I will need to join the resulant table with another table "users" on id.

I'm using Postgres 13.3

This answer is close to my needs, I just need it to be in different columns: https://stackoverflow.com/a/15847245

1 Answer 1

1

You can aggregate the emails into an array:

select id, array_agg(email) as all_emails
from the_table
group by id;

This can be used to join against the users table. To put the emails into columns, extract them from the array.

select u.*, 
       e.all_emails[1] as email1, 
       e.all_emails[2] as email2, 
       e.all_emails[3] as email3, 
       e.all_emails[4] as email4 
from users u
  join (
    select id, array_agg(email) as all_emails
    from the_table
    group by id
  ) e on e.id = u.id;

If you need more emails, add more expressions to the outer query. If an index position does not exist, null is returned instead (no error).

It is not possible to write query that dynamically returns a different number of columns each time you call it. The number, type and name of all columns of a query must be known before the query starts running.

1
  • Well, that function then needs to return a constant set of columns - or you need to specify the number (and names) of the columns when you call the function. One way or another you will have to write an expression for each result column. It is not possible to write query that dynamically returns a different number of columns each time you call it
    – user1822
    Commented Jul 4, 2021 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.