我们说我有2个结果集(2个查询)。
FIELDNAME VALUE
field1 20.00
field2 13.00
field3 4.00
FIELDNAME VALUE
field1 20.00
field2 14.00
field3 6.00
我知道query1 EXCEPT query2
应该给出
FIELDNAME VALUE
field2 13.00
field3 4.00
但我真正想要的是从查询的两个方面展示存在差异的任何情况:
FIELDNAME VALUE
field2 13.00
field3 4.00
field2 14.00
field3 6.00
这可能吗?我想我可以在一个临时表中做一个SELECT UNION。然后删除任何NOT EXISTS字段名不同的行。还有什么更简单的吗?
似乎我可以将INTERSECT,UNION和EXCEPT结合起来并以此结束,但没有太多的运气概念化。
答案 0 :(得分:2)
我认为您应该能够使用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)
其他方法是使用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)
答案 1 :(得分:0)
就像XOR操作:
DECLARE @Table1 TABLE(Name nvarchar(20), Value decimal)
DECLARE @Table2 TABLE(Name nvarchar(20), Value decimal)
INSERT INTO @Table1
VALUES
(N'field1', 20.00),
(N'field2', 13.00),
(N'field3', 4.00)
INSERT INTO @Table2
VALUES
(N'field1', 20.00),
(N'field2', 14.00),
(N'field3', 6.00)
SELECT *
FROM
(
SELECT *
FROM @Table1 AS t
EXCEPT (SELECT * FROM @Table2 AS t)
) AS a
UNION
SELECT *
FROM
(
SELECT *
FROM @Table2 AS t
EXCEPT (SELECT * FROM @Table1 AS t)
) AS b
答案 2 :(得分:0)
根据您的帖子,您已尝试使用INTERSECT,UNION和EXCEPT组合,但未获得输出。
尝试使用(INTERSECT,UNION和EXCEPT)来获取它。
DECLARE @Table1 TABLE(Name nvarchar(20), Value decimal(18,2))
DECLARE @Table2 TABLE(Name nvarchar(20), Value decimal(18,2))
INSERT INTO @Table1
VALUES
(N'field1', 20.00),
(N'field2', 13.00),
(N'field3', 4.00)
INSERT INTO @Table2
VALUES
(N'field1', 20.00),
(N'field2', 14.00),
(N'field3', 6.00)
select *From @Table1
union
select *From @Table2
except
select *From @Table1
intersect
select *From @Table2