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