如果两行不是同一数据,如何在联合中定义唯一值

时间:2019-04-22 08:46:07

标签: sql

我正在使用union创建一个简单的SQL查询,结果将正确返回,但是如果联合结果中有一个值包含两行,该如何在虚拟列中设置默认值?

如果结果为一个雇员返回了两个值,则虚拟列的第一个值为'N',第二个值为'Y'。

如果结果仅返回员工的一个值,则虚拟列为'Y'

如何实现?

Screenshot as example

这是我正在使用的查询

select 
    dbo.employee,
    dbo.starting_date 
from 
    table_1
union
select 
    dbo.employee,
    dbo.hiring_date 
from 
    table_2

2 个答案:

答案 0 :(得分:1)

具有CTE:

with cte as (
  select dbo.employee, dbo.starting_date date from table_1
  union all
  select dbo.employee, dbo.hiring_date date from table_2
)

select
  t.*,
  case when exists (
    select 1 from cte 
    where employee = t.employee and date > t.date 
  ) then 'N' else 'Y' end dummycolumn
from cte t

答案 1 :(得分:0)

您可以为此使用窗口功能:

select t.employee, t.date,
       (case when 1 = row_number() over (partition by t.employee order by t.date)
             then 'Y' else 'N'
        end) as dummy
from ((select t1.employee, t1.starting_date as date
       from table_1 t1
      ) union all
      (select t2.employee, t2.starting_date as date
       from table_2 t2
      )
     ) t
相关问题