我在下表中有一些示例数据
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
关于sql-server - 将 Union All 替换为 Or Sql Server,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60580901/