SQL Server query with same functionality as Excel VLookup

烈酒焚心 提交于 2019-12-06 08:53:52

问题


I have 2 columns of data that I need to compare with each other - Column A and Column 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.
  • But it may not have all the values in column B.

I need to find out which of the values in column B are also in column 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.
  • Column A and Column B are fields in 2 separate tables
  • There are no other columns in the 2 tables

Thanks for all your help!


回答1:


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:


The problem with a left join is that there might be duplicates in table 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://stackoverflow.com/questions/16472517/sql-server-query-with-same-functionality-as-excel-vlookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!