SQL Server查询具有与Excel VLookup相同的function
我有2列数据,我需要相互比较 – 列A和列B.
A栏:
Steve Jane Mary Peter Ed Scott Ted
B栏:
Peter Scott David Nancy
- 列A的数据量大于列B.
- 但它可能没有列B中的所有值
我需要找出列B中的哪些值也在列A中。
预计以上样本数据的输出:
Peter TRUE Scott TRUE David FALSE Nancy FALSE
- 需要使用SQL Server / T-SQL来获得这个输出。
- 列A和列B是2个独立表中的字段
- 2表中没有其他列
感谢你的帮助!
select b.columnb, case when a.columna is null then 'FALSE' else 'TRUE' end from tableb b left outer join tablea a on b.columnb = a.columna
左连接的问题是表A中可能有重复
如果这是一个问题,你可以这样做:
select b.col, (case when a.val is NULL then 'FALSE' else 'TRUE' end) from b left outer join (select distinct a.val from a ) a on b.col = a.val;
另一种expression方式是使用相关的子查询。 这将所有的逻辑放在select
:
select b.col, (case when exists (select 1 from a where a.val = b.col) then 'TRUE' else 'FALSE' end) from b