我在下表中有一些示例数据
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条件获得相同的结果,而不是两次查询同一张表,这是我尝试编写的查询,但未返回与上述查询相同的结果集
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)
让我知道是否可行。
如何使用交叉申请
示例
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
返回
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