如果数据基于SQL中的给定优先级存在,则返回行

时间:2015-07-20 13:46:43

标签: sql postgresql amazon-redshift

我正在尝试构建一个PostgreSQL语句,该语句根据具有给定优先级的电子邮件类型返回客户电子邮件。下面我有一个客户1和2的表。客户1有个人和公司电子邮件,而客户2有公司电子邮件。

我试图解决的问题是,如果客户首先存在并且如果没有返回公司,则返回客户个人电子邮件。因此,个人电子邮件优先于公司。这在PostgreSQL中甚至可能吗?

 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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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