条件自加入 SQL 服务器

Conditional self join SQL Server

我正在尝试根据条件自行加入。

有没有一种方法可以不使用 Union 来做到这一点? (联合工作正常,但我试图避免的查询大小加倍)

下面是我写的查询(任何建议或指导将不胜感激!)

Select 
    concat(de.EthnicityText ,' - ', dec2.EthnicityText) as 'Ethnicity'
from
    dl.DimEthnicity de
inner join 
    (select dec1.EthnicityParentId, dec1.EthnicityText
     from dl.dimethnicity dec1) as dec2 on de.EthnicityID = dec2.EthnicityParentId

union all

select de.EthnicityText as 'Ethnicity'
from dl.DimEthnicity de
where de.EthnicityParentId is null

假设您想要 return 所有值,即使 ParentID 为空。

select a.EthnicityText + case when b.EthnicityText is null then '' else ' - ' + b.EthnicityText end
from DimEthnicity a
left join DimEthnicity b on b.EthnicityID = a.EthnicityParentID

左联接允许您查找的条件(只有 return 自联接行存在时)。有关左连接的更多信息:https://www.w3schools.com/sql/sql_join_left.asp