根据另一列Oracle SQL的优先级选择值

时间:2017-04-04 19:25:28

标签: sql oracle

我只想为每个 ID 选择一个电子邮件地址,如果 id 同时包含工作和个人电子邮件,我只想显示工作电子邮件。

with emails as(
select '1' id, 'work' email_type, 'abc@gmail.com' email from dual union all
select '2' id, 'work' email_type, '123@yahoo.com' email from dual union all
select '2' id, 'personal' email_type, '456@msn.com' email from dual union all
select '3' id, 'personal' email_type, 'test@work.com' email from dual
)

对于这个例子,我想显示:

id    email_type    email
1     work          abc@gmail.com
2     work          123@yahoo.com
3     personal      test@work.com

3 个答案:

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

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

答案 2 :(得分:0)

您可以使用子查询来确定是否有工作电子邮件。使用样本数据,您可以使用MAX函数返回" work"如果它存在,则键入,如果它不存在,它将返回" personal"。再加上那将得到适当的结果。

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