我有兩個表格,我想創建一個視圖來加入它們。如何在SQL Server中使用CAST連接兩個表格
我創建了一個圖片來解釋我的問題。如上圖所示,表1中的值是唯一的,我想知道表1中的值是否存在於表2中。我想添加一個包含「NO」的列如果它不存在,如果它包含額外的列,則必須包含「YES」。
我希望我能解釋一下自己。
我有兩個表格,我想創建一個視圖來加入它們。如何在SQL Server中使用CAST連接兩個表格
我創建了一個圖片來解釋我的問題。如上圖所示,表1中的值是唯一的,我想知道表1中的值是否存在於表2中。我想添加一個包含「NO」的列如果它不存在,如果它包含額外的列,則必須包含「YES」。
我希望我能解釋一下自己。
您可以將table2與table1留在一起,查看是否存在任何行。
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;
我會做這樣的:
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)
上的索引。
;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
你可以用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);
http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code -on那麼當灰化-A-問題/ 285557#285557 –