如何从 UNION 中删除重复项但忽略一列

How to remove duplicates out of the UNION but ignore one column

考虑以下 table 数据:

FirstName LastName Department
Steve Colton Accounting
Stacy Beckham Finance
Mary Messi Finance
Steve Colton Finance
Michael Gretsky Finance

如您所见,Steve Colton 在会计和财务部门工作。
我想要一个应该 return 史蒂夫一次的查询。

我可以执行以下操作,但代码似乎比需要的多:

insert #FinalData(FirstName, LastName, Department)
select * from MyTable where Department = 'Accounting'

insert #FinalData(FirstName, LastName, Department)
select * from from MyTable mt1 where mt1.Department = 'Finance'
  and not exists (
      select 1 from #FinalData fd 
      where fd.FirstName = mt1.FirstName and fd.LastName = mt1.LastName
  )

我正在寻找一种更简洁的方法来执行此操作。我试过 UNION 但似乎没有办法排除列以进行重复数据删除。

还有其他方法吗?

您可以使用 row_number()。如果你想每个名字一行(你的问题暗示),那么:

select t.*
from (select t.*,
             row_number() over (partition by firstname order by department) as seqnum
      from MyTable 
     ) t
where seqnum = 1;

这将为重复项选择“会计”而不是“财务”。