SQL Server查詢與Excel VLookup具有相同的功能

[英]SQL Server query with same functionality as Excel VLookup


I have 2 columns of data that I need to compare with each other - Column A and Column B.

我有兩列數據需要相互比較 - A列和B列。

Column A:

Steve
Jane
Mary
Peter
Ed
Scott
Ted

Column B:

Peter
Scott
David
Nancy
  • Column A has a larger amount of data than column B.
  • A列的數據量大於B列。

  • But it may not have all the values in column B.
  • 但它可能沒有列B中的所有值。

I need to find out which of the values in column B are also in column A.

我需要找出B列中的哪些值也在A列中。

Output expected for above sample data:

上述樣本數據的預期輸出:

Peter   TRUE
Scott   TRUE
David   FALSE
Nancy   FALSE
  • Need to use SQL Server / T-SQL to get this output.
  • 需要使用SQL Server / T-SQL來獲取此輸出。

  • Column A and Column B are fields in 2 separate tables
  • A列和B列是2個單獨表格中的字段

  • There are no other columns in the 2 tables
  • 2個表中沒有其他列

Thanks for all your help!

感謝你的幫助!

2 个解决方案

#1


9  

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

#2


4  

The problem with a left join is that there might be duplicates in table A.

左連接的問題是表A中可能存在重復。

If this is an issue, you can do this:

如果這是一個問題,您可以這樣做:

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;

An alternative way of expressing this is using a correlated subquery. This puts all the logic in the select:

另一種表達方式是使用相關子查詢。這將所有邏輯放在選擇中:

select b.col,
       (case when exists (select 1 from a where a.val = b.col)
             then 'TRUE'
             else 'FALSE'
       end)
from b

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/05/09/16bfebff1723bad1acb6bce3d972e3a2.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com