将具有不等数量表达式的两列合并为一列,并获得唯一值

时间:2015-05-18 19:04:53

标签: sql-server

我在两个表中有两列。我需要将这两列合并为一列,同时确保结果列中的所有值都是唯一的。像这样:

Alice   Alice
Andy    NULL
Bob     Bob
Carl    NULL
Jack    Jack
Joan    NULL
Kai     NULL
Mary    Mary
NULL    Mo
Tony    NULL
NULL    Trick
Judy

Alice
Andy
Bob
Carl
Jack    
Joan    
Kai     
Mary    
Mo      
Tony
Trick
Judy

我无法使用UNION,因为这些列可能并不总是具有相同数量的表达式,并且它返回如下所示的错误。我该怎么办?或者可以这样做吗?

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

3 个答案:

答案 0 :(得分:1)

鉴于您的数据(如果它们都在那里,两列中的值相同),那么:

select distinct coalesce(a, b)
from table t;

如果这个条件不成立,那么你需要一个union,Giorgi的答案会解释。

答案 1 :(得分:0)

如果,我理解您的问题,那么您可以对两个列使用CASE语句

create table tempcombine(
a varchar(20)
)

create table tempcombine1(
b varchar(20)
)

--truncate table tempcombine
insert into tempcombine values ('Alice')
insert into tempcombine values ('Andy')
insert into tempcombine values ('Bob')
insert into tempcombine values ('Carl')
insert into tempcombine values (NULL)
insert into tempcombine values ('Judy')


insert into tempcombine1 values ('Alice')
insert into tempcombine1 values (NULL)
insert into tempcombine1 values ('Bob')
insert into tempcombine1 values (NULL)
insert into tempcombine1 values ('Trick')

然后您可以使用CASE获得所需的结果

SELECT *FROM 
(
 Select distinct
 Case when a = b then a
     When a IS NULL then b
     When b IS null then a end UniqueColumnName
From tempcombine, tempcombine1) as ab 
where ab.UniqueColumnName is not null

答案 2 :(得分:0)

简单UNION

declare @t1 table(Alice varchar(10))
declare @t2 table(Alice varchar(10))


insert into @t1 values
('Alice'),
('Andy'),
('Bob'),
('Carl'),
('Jack'),
('Joan'),
('Kai'),
('Mary'),
(NULL),
('Tony'),
(NULL),
('Judy')


insert into @t2 values
('Alice'),
(NULL),
('Bob'),
(NULL),
('Jack'),
(NULL),
(NULL),
('Mary'),
('Mo'),
(NULL),
('Trick')


select Alice from @t1 where Alice is not null
union
select Alice from @t2 where Alice is not null

输出:

Alice
Andy
Bob
Carl
Jack
Joan
Judy
Kai
Mary
Mo
Tony
Trick