0

I have the following table in Postgres 10.4.

Name   Email          EmailType 
--------------------------------------      
John   [email protected]   Primary Email   
John   [email protected]   Secondary Email
John   [email protected]  Work Email
Jack   [email protected]   Primary Email   
Jack   [email protected]   Secondary Email
Jim    [email protected]    Primary Email   

How can I assign value in col4 based on the values in Name (assume that the name is UNIQUE in this table) and EmailType column. For every person (Name column), I want to check how many email types (EmailType column) they have and then sort of concatenate the person name and the email type into a new column. Something like below.

Name   Email          EmailType         Col4
-----------------------------------------------------------------------------------------
John   [email protected]   Primary Email     John: Primary Email, Secondary Email, Work Email
John   [email protected]   Secondary Email
John   [email protected]  Work Email
Jack   [email protected]   Primary Email     Jack: Primary Email, Secondary Email
Jack   [email protected]   Secondary Email
Jim    [email protected]    Primary Email     Jim: Primary Email

I thought of using a CASE statement, but unable to get it to work. Any help on this will be greatly appreciated.

1
  • Create a view. Or at least use triggers. Commented Apr 16, 2024 at 13:58

1 Answer 1

1

You can do this using window functions and conditional string aggregation.

select name, email, emailtype, 
 case when rn=1 then string_agg(emailtype,', ') over (partition by name) end col4
from
(
 select *, row_number() over (partition by name order by emailtype) rn
 from the_table
) t;

DB Fiddle

And - as @jarlh commented - create a view using the query.

Sign up to request clarification or add additional context in comments.

3 Comments

Your solution works great. But I am trying to achieve this in Adobe's query service platform which does not support the string_agg function. [Here](experienceleague.adobe.com/en/docs/experience-platform/query/… are the list of functions which it supports. I was wondering if there is any other alternative to string_agg.
Maybe collect_list(expr)?
It worked. I was so absorbed in work, that I missed going through other functions. But thank you for pointing me in the right direction. Much appreciated.

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.