Sql server 使用EXCEPT或INTERSECT仅显示不匹配的行
假设我有2个结果集(2个查询) 我知道Sql server 使用EXCEPT或INTERSECT仅显示不匹配的行,sql-server,sql-server-2008,Sql Server,Sql Server 2008,假设我有2个结果集(2个查询) 我知道query1,但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。然后删除不存在具有不同值的
query1,但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。然后删除不存在具有不同值的fieldname的所有行。有更简单的吗
似乎我可以以某种方式将INTERSECT、UNION和Exception组合起来,最终得到这个,但在概念化方面没有太多运气。我认为您应该能够通过使用Exception
两次并在结果上使用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)
就像手术一样:
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
根据您的帖子,您已经尝试了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
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