使用 EXCEPT 或 INTERSECT 仅显示不匹配的行

JL *_*ret 5 sql-server sql-server-2008

假设我有 2 个结果集(2 个查询)。

FIELDNAME   VALUE
field1      20.00
field2      13.00
field3      4.00

FIELDNAME   VALUE
field1      20.00
field2      14.00
field3      6.00
Run Code Online (Sandbox Code Playgroud)

我知道query1 EXCEPT query2应该给

FIELDNAME   VALUE
field2      13.00
field3      4.00
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是从查询的两侧显示任何存在差异的情况:

FIELDNAME   VALUE
field2      13.00
field3      4.00
field2      14.00
field3      6.00
Run Code Online (Sandbox Code Playgroud)

那可能吗?我想我可以在临时表中执行 SELECT UNION 。然后删除具有不同值的 NOT EXISTS 字段名的任何行。有没有更简单的?

似乎我可以以某种方式组合 INTERSECT、UNION 和 EXCEPT 并最终得到这个,但没有太多运气概念化。

dot*_*tom 4

我认为你应该能够通过使用EXCEPT两次并使用UNION ALL结果来获得你需要的东西:

-- records from the table1 that are not in table2
(SELECT * FROM table1 
EXCEPT 
SELECT * FROM table2)

UNION ALL

-- records from the table2 that are not in table1
(SELECT * FROM table2 
EXCEPT 
SELECT * FROM table1)
Run Code Online (Sandbox Code Playgroud)

其他方法是使用 组合所有表UNION,然后使用EXCEPT消除所有相交记录:

-- Union of both tables
(SELECT * FROM table1 
UNION ALL
SELECT * FROM table2)

EXCEPT   -- Exclude the records ...

-- ... that are in both tables
(SELECT * FROM table1 
INTERSECT 
SELECT * FROM table2)
Run Code Online (Sandbox Code Playgroud)