Sample data -
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
Now, I'm trying to join/merge column 'name' and 'name2' followed by remove duplicates and shows value as below - Any thoughts ?
Name
abc
ddd
yyy
zzz
I need to get this done using CASE statement ie, sample code is below. (Albeit this can be achieved by using UNION but I need to use CASE Statement)
select case 'b'
when 'a'
then name
when 'b'
then coalesce (name , name2 )
end as NAME from #test
This is awful and should really be done using a UNION, but I think it's what you were after in this example:-
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
Really though, you should have something like this:-
select name from #test
union
select name2 from #test
Well one of the way to get desired result is by using Union
and another alternate way is this -
SELECT id
,(
SELECT max(name1)
FROM (
VALUES (name)
,(name2)
) res(name1)
) AS name
FROM #test
Result
id Name
--------
1 abc
1 ddd
1 yyy
1 zzz
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.