将 Union All 替换为 Or Sql Server

Replace Union All with Or Sql Server

我有以下 table 和一些示例数据

Create table dbo.Test_2020
(
 id int identity(1,1),
 level_cd_1 varchar(10) null,
 level_cd_2 varchar(10) null
)

insert into dbo.Test_2020

select 'cd_1_01',null
union all
select 'cd_1_02',null
union all
select 'cd_1_03','cd_2_01'
union all
select null, 'cd_2_02'
union all
select null, 'cd_2_03'
union all
select 'cd_1_04', 'cd_2_04'

下面是用于从两列获取非空值的查询:level_cd_1 & level_cd_2

 select id, level_cd_1 as level_cd from Test_2020 where level_cd_1 is not null
 union all
 select id, level_cd_2  from Test_2020 where level_cd_2 is not null

问题是我能否使用 OR 条件而不是查询相同的 table 两次来获得相同的结果,这是我尝试编写的查询,但没有返回与上述查询相同的结果集

 select id, coalesce(level_cd_1,level_cd_2)as leve_cd from Test_2020 where 
  (level_cd_1 is not null or level_cd_2 is not null)

如果可行,请告诉我。

使用 CROSS APPLY 怎么样

例子

Select A.ID
      ,B.*
 From  Test_2020 A
 Cross Apply ( values ( level_cd_1 )
                     ,( level_cd_2 )
             ) B(level_cd)
 Where level_cd is not null

Returns

ID  level_cd
1   cd_1_01
2   cd_1_02
3   cd_1_03
3   cd_2_01
4   cd_2_02
5   cd_2_03
6   cd_1_04
6   cd_2_04