返回两个表之间的不同行

时间:2017-01-03 13:51:21

标签: sql sql-server-2008

有没有办法检查并返回两个表之间不常见的所有行?

表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    

4 个答案:

答案 0 :(得分:2)

select * from table1
union 
select * from table2
except
(select * from table1 intersect select * from table2)

答案 1 :(得分: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'

答案 2 :(得分:0)

您可以使用EXCEPT,例如

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

(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);

答案 3 :(得分: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'
相关问题