简体   繁体   English

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

[英]Select value based on priority of another column Oracle SQL

I would like to select only one email address per id , if the id has both a work and personal email, I would only like to display the work email. 我只想为每个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
)

For this example I would like to display: 对于此示例,我想显示:

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

You can prioritize those values in row_number and get the first row for each id. 您可以在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

Assuming only possible value for email_type are work and personal, you can use window function row_number : 假设email_type的唯一值是work和personal,则可以使用窗口函数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;

You can use a subquery to figure out if there is a work email or not. 您可以使用子查询来确定是否有工作电子邮件。 With your sample data, you can use the MAX function to return the "work" type if it exists, and if it doesn't it will just return "personal". 对于样本数据,可以使用MAX函数返回“工作”类型(如果存在),如果不存在,则仅返回“个人”类型。 Joining back on that will give the appropriate result. 重新加入该链接将给出适当的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM