1

我试图构建一个postgresSQL语句,该语句根据具有给定优先级的电子邮件类型返回客户电子邮件。下面我有一个客户1和2的桌子。客户1拥有个人和公司的电子邮件,而客户2拥有公司的电子邮件。如果数据基于SQL中给定的优先级存在,则返回行

我想解决的问题是,如果客户第一个存在,并且如果不能退回公司,则会返回客户的个人电子邮件。所以,个人电子邮件优先于公司。这在postgresSQL中甚至是可能的。

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

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

我现在正在尝试的并不是真的有效。它返回的所有行和不过滤

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

回答

2

一种选择是使用有条件聚集:

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

下面是使用另一种选择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 
+0

我给这是一个尝试。谢谢! – user1026498

0

您可以用公用表表达式(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