2017-04-04 129 views
0

的優先選擇價值,我想每ID只選擇一個電子郵件地址,如果ID既有工作和個人電子郵件,我只想以顯示工作電子郵件。基於另一列的Oracle SQL

with emails as(
select '1' id, 'work' email_type, '[email protected]' email from dual union all 
select '2' id, 'work' email_type, '[email protected]' email from dual union all 
select '2' id, 'personal' email_type, '[email protected]' email from dual union all 
select '3' id, 'personal' email_type, '[email protected]' email from dual 
) 

對於這個例子,我想顯示:

id email_type email 
1  work   [email protected] 
2  work   [email protected] 
3  personal  [email protected] 
+0

爲什麼這樣?邏輯是什麼? – Rahul

+0

我正在創建一個加載文件,如果我已經有一個工作電子郵件,我不會做任何事情,但如果我有個人電子郵件,我會將其作爲工作電子郵件加載。爲了簡單起見,我更改了電子郵件類型的名稱。 – canada48978

回答

1

假設爲EMAIL_TYPE唯一可能的值是工作和個人,可以使用窗口函數row_number

select * 
from (
    select t.*, 
     row_number() over (
      partition by id order by email_type desc 
      ) as seqnum 
    from emails t 
    ) t 
where seqnum = 1; 
1

可以在row_number這些值的優先級,並獲得第一排的每個ID。

select id,email_type,email 
from (select id,email_type,email 
     ,row_number() over(partition by id order by case when email_type='work' then 1 else 2 end) as rn 
     from emails) t 
where rn = 1 
0

您可以使用子查詢,以找出是否有一個工作電子郵件或沒有。使用示例數據,可以使用MAX函數返回「工作」類型(如果存在),如果不存在,它將僅返回「個人」類型。加入這將得到適當的結果。

WITH T1 AS (SELECT id, MAX(email_type) AS e_type FROM table_name GROUP BY id) 
SELECT T1.id, T1.e_type, T2.email 
FROM T1 LEFT JOIN table_name T2 ON T1.id = T2.id AND T1.e_type = T2.email_type 
ORDER BY T1.id