2017-01-06 13 views
1

2つのテーブルがあり、それらを結合するためのビューを作成したいと考えています。SQL ServerでCASTと2つのテーブルを結合する方法

IMAGE

私は私の問題を説明するために画像を作成しました。上記の図のように、表1の値はユニークで、表1の値が表2に存在するかどうかを知りたいと思います。 "NO"を含む列を追加したいと思います。存在しない場合は、追加の列に "YES"が含まれている必要があります。

私は自分自身を説明できることを願っています。

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code -on-so-ask-a-question/285557#285557 –

答えて

1

table1を使用してtable2を結合したままにして、行が存在するかどうかを確認できます。

select t1.col, case when count(t2.col) = 0 then 'No' else 'Yes' end 
from table1 t1 
left join table2 t2 
on t1.col = t2.col 
group t1.col; 
2

私はこれを行うだろう:これは、この目標を達成するための最も効率的な方法でなければなりません

select t1.*, 
     (case when exists (select 1 from table2 t2 where t2.col = t1.col) 
      then 'YES' 
      else 'NO' 
     end) as flag 
from table1 t1; 

。最高のパフォーマンスを得るには、table2(col)のインデックスが必要です。

0
;with A as 
(select v from (values ('a'),('b'),('c'),('d'),('e')) v(v)) 
, B as 
(select v from (values ('a'),('a'),('b'),('b'),('b'),('c'),('c'),('d')) v(v)) 
-- This is where the magic happens 
select 
distinct a.v,case when b.v is null then 'NO' else 'YES' end existsinb 
from A 
left join B 
on a.v=b.v 
order by v 
0

あなたはfull joinで両側を確認することができます。

create view dbo.MyViewOfMissingValues 
as 
select 
    isnull(t1.col, t2.col) col, 
    case 
     when t2.col is null then 'No (missing in t2)' 
     when t1.col is null then 'No (missing in t1)' 
     else 'Yes' -- contained in both tables 
    end col_status 
from table1 t1 
full join table2 t2 
    on t1.col = t2.col 
group isnull(t1.col, t2.col); 
関連する問題