我有两列数据需要相互比较:
第1栏:
People
Trust
Corporate
第2栏:
People
People
People
Company
Corporate
Corporate
Corporate
Company
Trust
Trust
COLUMN 1比COLUMN 2短,但是是站立数据与COLUMN 2进行比较。我想找到COLUMN 2中不属于COLUMN 1的值。
这样的结果是我正在寻找的:
People TRUE
People TRUE
People TRUE
Company FALSE
Corporate TRUE
Corporate TRUE
Corporate TRUE
Company FALSE
Trust TRUE
Trust TRUE
这些列位于两个不同的表中。我正在使用SQL。 有什么建议吗?
答案 0 :(得分:2)
使用CASE WHEN EXISTS
select Column2,
case
when exists (select Column1 from Table1 T1 where T1.Column1 = Column2)
then 'TRUE'
else 'FALSE'
from Table2
答案 1 :(得分:2)
其他答案都是正确的,但我总是发现使用LEFT JOIN
更快:
(我不知道这是不是我的看法,或者它是否真的更具表现力)
SELECT
T2.COLUMN,
CASE WHEN T1.COLUMN IS NULL THEN 'FALSE' ELSE 'TRUE' END EXISTENT
FROM TABLE_2 T2
LEFT OUTER JOIN TABLE_1 T1
ON T2.COLUMN = T1.COLUMN
答案 2 :(得分:0)
答案都是正确的,但如果您想要实际的真或假而不是字符串,您可以转换为位字段:
declare @temp1 table (column1 varchar(50))
declare @temp2 table (column1 varchar(50))
insert into @temp1 (column1) values ('people')
insert into @temp1 (column1) values ('trust')
insert into @temp1 (column1) values ('corporate')
insert into @temp2 (column1) values ('People')
insert into @temp2 (column1) values ('People')
insert into @temp2 (column1) values ('People')
insert into @temp2 (column1) values ('Company')
insert into @temp2 (column1) values ('Corporate')
insert into @temp2 (column1) values ('Corporate')
insert into @temp2 (column1) values ('Corporate')
insert into @temp2 (column1) values ('Company')
insert into @temp2 (column1) values ('Trust')
insert into @temp2 (column1) values ('Trust')
select t2.column1, convert(bit, case when t1.column1 is null then 0 else 1 end)
from @temp2 t2
left join @temp1 t1 on t2.column1 = t1.column1