[英]sql server compare two column from different table
我有兩個表包含兩個表中的一列
表 1 項
表2項目
如果 table1 和 table2 的 item 列中的所有值都完全匹配,我想要 boolean 結果 true/false。 例如兩個表的列值
item item
apple apple
boy boy
cat cat
這應該返回 true
item item
apple apple
boy boy
cat dog
應該返回假
您可以使用full join
和聚合:
select (case when count(*) = 0 then 'true' else 'false' end)
from t1 full join
t2
on t1.item = t2.item
where t1.item is null or t2.item is null;
這算失誤。 如果沒有,則表是相同的。
或者沒有where
子句:
select (case when count(t1.item) = count(t2.item) then 'true' else 'false' end)
from t1 full join
t2
on t1.item = t2.item
where t1.item is null or t2.item is null;
注意:就像您問題中的數據以及一般問題一樣,這假設項目是唯一的。
您只能通過從左到右和從右到左連接兩個表來檢查記錄是否存在於一側或另一側。 如果有任何記錄不匹配, false
,否則為true
。
select case when exists (
select top 1 1
from Table1 t1
left join Table2 t2 on t2.item = t1.item
where t2.item is null
union all
select top 1 1
from Table2 t2
left join Table1 t1 on t1.item = t2.item
where t1.item is null
)
THEN 'false'
ELSE 'true'
END as result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.