返回左连接中任一表中的所有列

时间:2017-11-29 14:11:27

标签: sql sql-server tsql

如果左连接表没有值,我试图从table1返回行,否则我将返回所有列的左连接表值

select 
 (case when u2.Id is null then u1.Name else u2.Name end) as Name,
 (case when u2.Id is null then u1.Department else u2.Department end) as Department,
 (case when u2.Id is null then u1.Office else u2.Office end) as Office
from user u1
left join user u2 on u1.TerminationDate = u2.TerminationDate

这是一个可行的解决方案,但是没有更好的方法,我不需要放置这么多case... when...语句,因为我在示例中只包含了很少的列,但是有很多列我觉得应该有一些更好的方法来实现这一目标。

1 个答案:

答案 0 :(得分:0)

使用COALESCE

select 
coalesce(u2.Name, u1.Name) as Name,
coalesce(u2.Id, u1.Department) as Department,
coalesce(u2.Id, u1.Office) as Office,
from user u1
left join user u2 on u1.TerminationDate = u2.TerminationDate