样本数据 -
CREATE TABLE dbo.#test
(
id int NOT NULL,
name varchar (10) NULL,
name2 varchar (10) null
);
insert into #test values ('1','abc','abc')
insert into #test values ('1','abc','yyy')
insert into #test values ('1','abc','zzz')
insert into #test values ('1','abc','ddd')
select * from #test
现在,我尝试加入/合并“名称”和“名称2”列,然后删除重复项并显示如下值-有什么想法吗?
Name
abc
ddd
yyy
zzz
我需要使用CASE语句来完成此操作,即下面的示例代码。(尽管这可以通过使用UNION来实现,但是我需要使用CASE语句)
select case 'b'
when 'a'
then name
when 'b'
then coalesce (name , name2 )
end as NAME from #test
这太糟糕了,实际上应该使用UNION来完成,但是我想这就是您在此示例中追求的:-
select
case
when (select count(*) from #test b where b.name = a.name2) > 1 then a.name
else a.name2
end as Name
from #test a
确实,您应该有这样的东西:
select name from #test
union
select name2 from #test
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句