Return 行,如果数据存在于 SQL 中的给定优先级

Return rows if data exists based on a given priority in SQL

我正在尝试形成一个 PostgreSQL 语句,该语句 return 是基于具有给定优先级的电子邮件类型的客户电子邮件。下面我有一个 table 客户 1 和客户 2。客户 1 有个人和公司的电子邮件,而客户 2 有公司的。

我要解决的问题是先 return 编辑客户的个人电子邮件,如果不存在,则 return 公司。因此,个人电子邮件优先于公司。这在 PostgreSQL 中甚至可能吗?

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

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

我现在尝试的方法并没有真正奏效。它 return 包含所有行并且不过滤

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

一种选择是使用条件聚合:

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

您可以使用常见的 table 表达式 (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