Search code examples
sqlpostgresqlpostgresql-10

PostgreSQL populate a column based on other 2 columns


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.


Solution

  • 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.