2

I am trying to form a PostgreSQL statement that returns a customer email based on the email type with a given priority. Below I have a table with customers 1 and two. Customer 1 has both personal and company emails whereas customer 2 has on the company.

The problem I am trying to solve is returned the customers personal email if it exists first and if not return the company. So, the personal email is given priority over the company. Is this even possible in PostgreSQL?

 customers
+------------+
| cusomterID |
+------------+
| 1          |
| 2          |
+------------+

customer_email
+------------+-------------+
| cusomterID | email_type  |
+------------+-------------+
| 1          | personal    | -- 0
| 2          | company     | -- 1
| 1          | company     | -- 1
+------------+-------------+

What I am trying now is not really working. It returns all of the rows and does not filter

SELECT *
FROM customers cs
JOIN cumstomer_email cm ON cm.customerId = cs.customreId
WHERE COALESCE(cm.email_type,0) IN (0,1)

2 Answers 2

2

One option would be to use conditional aggregation:

select customerId, max(case when email_type = 'personal' then email_type
                       else email_type 
                       end) email_type
from customer_email
group by customerId

And here's another option using row_number():

select customerId, email_type
from (select *, 
           row_number() over (partition by customerId 
                              order by email_type = 'personal' desc) rn
      from customer_email) t
where rn = 1
Sign up to request clarification or add additional context in comments.

1 Comment

I'll give this a try. Thank you!
0

You could do this with a common table expression (CTE):

with emailPriority as (
    select customerId,
           max(email_type) emailType
    from   customer_email
    group by customer_id)
select  cs.*, cm.email_address
from    customers cs join emailPriority ep on cs.customerId = ep.customerId
        join customer_email cm on cm.email_type = ep.email_type

Comments

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.