SQL Server:join if

时间:2017-08-15 13:19:29

标签: sql-server-2008

我有下表。我需要创建一个首先捕获所有者名称的连接,如果为null则使用secondaryname

from table A
 left join HR on a.ownername = hr.id
--or a.secondaryname = hr.id  this does not work
and hr.active = y

表A

 ID     SecondaryName    OwnerName    
 1        jaj              null         
 2        jat              jat
 3        joa              nel

表HR表

 Role            ID     Active
 Senior          jat     Y
 Senior          nel     Y
 Specialist      jaj     Y

1 个答案:

答案 0 :(得分:1)

您可以使用COALESCE

left join HR on COALESCE(a.OwnerName, a.SecondaryName) = hr.id