2017-01-03 6 views
0

2つのテーブル間で共通でないすべての行をチェックして返す方法はありますか?2つのテーブル間で異なる行を返す

表1:

pk name date 
102 John 1/1/16 
101 Bob  1/1/17 

表2:

pk name date 
102 John 1/1/16 
104 Bob  1/1/17 
105 Ted  1/1/18 

理想的には、私はまた、日付のクエリを制限することができます。だから私は日< 1/1/18によって制限する場合、結果は次のようになります。

table pk name date 
1  101 Bob  1/1/17 
2  104 Bob  1/1/17  

答えて

2
select * from table1 
union 
select * from table2 
except 
(select * from table1 intersect select * from table2) 
0
select * from table1 t1 
where not exsits (
    select 1 from table2 t2 where t2.pk = t1.pk 
) and t1.Date < '2018/1/1' 

union all 

select * from table2 t2 
where not exsits (
    select 1 from table1 t1 where t2.pk = t1.pk 
) and t2.Date < '2018/1/1' 
0

あなたはこのような

select pk, 
    name, 
    date from table1 
except 
select pk, 
    name, 
    date from table2; 

ためEXCEPTを使用します(OR)NOT INを使用することができますオペレータはUNIONと同様に

select * from table1 where pk not in (select distinct pk from table2); 
union 
select * from table2 where pk not in (select distinct pk from table1); 
0

サンプルデータでより正確に:

SELECT * FROM 
((SELECT 1 as [table],* FROM 
     (SELECT * FROM #TABLE_1 
     EXCEPT 
     SELECT * FROM #TABLE_2) AS Inner1) 
UNION 
(SELECT 2 as [table],* FROM 
     (SELECT * FROM #TABLE_2 
     EXCEPT 
     SELECT * FROM #TABLE_1) AS Inner2)) AS Final 
WHERE Final.date < '2018-01-01' 
関連する問題