我有一个有两列的表。我想比较第一列的每一行与第二列中的所有行。如果匹配,我需要在第3列中插入yes,否则我需要插入no。
First second
A B
C D
E A
X c
输出应为
First second yesOrno
A B yes
C D yes
E A NO
X c NO
答案 0 :(得分:2)
使用相同表格的EXISTS
。
UPDATE T1 SET
ThirdColumn = CASE WHEN EXISTS (
SELECT
'a SecondColumn match exists'
FROM
YourTable AS T2
WHERE
T1.FirstColumn = T2.SecondColumn) THEN 'Yes' ELSE 'No' END
FROM
YourTable AS T1
答案 1 :(得分:2)
SELECT
First, Second,
CASE WHEN EXISTS (
SELECT * FROM Table t2
WHERE t2.Second = t1.First)
THEN 'Yes' ELSE 'No' END AS YesOrNo
FROM
Table t1
答案 2 :(得分:0)
你可以通过自我加入获得它,如下所示
select T1.First,T1.second,(case when T2.second is null then 'no' else 'yes' end) as yesOrno from T as T1 left join T as T2
on T1.First=t2.second
检查sql小提琴:SQL Fiddle
答案 3 :(得分:0)
你可以这样做:
declare @t table (
C1 char(1),
C2 char(1)
)
insert @t
values ('A','B'),
('C','D'),
('E','A'),
('X','C')
select t1.C1,t1.C2, case when t2.C2 is null then 'No' else 'Yes' end YesOrNo
from @t t1 left join @t t2
on t1.C1 = t2.C2
编写此基本查询的方法有很多种。