【问题标题】:Creating a field for Email Address in Employee table where Email Address Type is Work, if Null then Personal Email在电子邮件地址类型为工作的员工表中为电子邮件地址创建一个字段,如果为空,则为个人电子邮件
【发布时间】:2019-11-07 21:26:14
【问题描述】:

我有一张活跃员工的表格,我需要从电子邮件表格中输入他们的电子邮件地址。一些员工有两个电子邮件记录(工作和个人)。我想带入工作电子邮件,如果为空,则带入个人电子邮件,全部放在一个列中。

我尝试创建两列,一列用于工作,一列用于个人,然后使用案例语句创建新列,但您不能在同一查询中引用别名。

我对 SQL 很陌生,所以我不确定 CTE 或 Temp 表或其他什么是我的答案,但我一直在旋转我的轮子。 (这对我来说在 Excel 中使用 vlookup 很简单,嵌套在 if/then 语句中)

【问题讨论】:

    标签: sql


    【解决方案1】:

    这是执行此操作的一种方法,使用条件聚合和coalesce()

    select empid,
           coalesce(max(case when emailtype = 'W' then email end),
                    max(case when emailtype = 'P' then email end),
                    max(email)
                   ) as preferred_email
    from emailaddress
    group by empid;
    

    我应该指出,coalesce() 的条件聚合有点小技巧。这里有两种更常规的方法:

    select ea.*
    from (select ea.*,
                 row_number() over (partition by empid order by emailtype desc) as seqnum
          from emailaddress ea
         ) ea
    where seqnum = 1;
    

    或者,假设每个员工的每种类型最多有一封电子邮件:

    select ea.*
    from emailaddress ea
    where ea.emailtype = 'W'
    union all
    select ea.*
    from emailaddress ea
    where ea.emailtype = 'H' and
          not exists (select 1
                      from emailaddress ea2
                      where ea2.empid = ea.empid and
                            ea2.emailtype = 'W'
                     );
    

    【讨论】:

    • 非常感谢这个工作!我看着合并,但永远不会得到这个
    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 2016-11-04
    • 2015-01-23
    • 2018-08-21
    • 2018-04-16
    • 2012-10-12
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多