我正在使用union
创建一个简单的SQL查询,结果将正确返回,但是如果联合结果中有一个值包含两行,该如何在虚拟列中设置默认值?
如果结果为一个雇员返回了两个值,则虚拟列的第一个值为'N',第二个值为'Y'。
如果结果仅返回员工的一个值,则虚拟列为'Y'
如何实现?
这是我正在使用的查询
select
dbo.employee,
dbo.starting_date
from
table_1
union
select
dbo.employee,
dbo.hiring_date
from
table_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