显示table1中的记录和table2中的记录,表1中不存在这些记录

时间:2016-11-23 19:55:56

标签: sql sql-server

我有两个表,每个表包含三个属性。我希望显示table 1table 2中的所有记录,仅提取table 1中不存在的记录。

表1

  ID   Percentage  OrderDate
+----+------------+----------+
  1      2.0       2015-05-08
  1      5.0       2014-05-08 
  1      19.65     2013-05-08
  1      5.06      2012-05-08
  1      98.0      2011-05-08
  1      8.56      2010-05-08
+----+------------+----------+

表2

  ID   Percentage  OrderDate
+----+------------+----------+
  1      45.5      2015-05-08
  1      45.23     2014-05-08 
  1      12.00     2013-05-08
  1      6.45      2012-05-08
  1      18.0      2011-05-08
  1      5.2       2010-05-08
  1      12.0      2009-05-08
  1      22.78     2008-05-08 
  1      48.9      2007-05-08
  1      7.89      2006-05-08
  1      17.96     2005-05-08
  1      11.3      2004-05-08
+----+------------+----------+

3 个答案:

答案 0 :(得分:0)

您可以使用EXCEPT keyword

SELECT ID, Pourcentage, OrderDate
FROM table1
UNION
(
    SELECT ID, Pourcentage, OrderDate
    FROM table2
    EXCEPT
    SELECT ID, Pourcentage, OrderDate
    FROM table1
)

答案 1 :(得分:0)

根据您所比较的列,您可以使用以下内容。

SELECT t1.ID, t1.Percentage, t1.OrderDate
FROM table1 t1
UNION ALL
SELECT t2.ID, t2.Percentage, t2.OrderDate
FROM table1 t1
INNER JOIN table2 t2 ON t2.ID <> t1.ID AND t2.Percentage <> t1.Percentage AND t2.OrderDate <> t1.OrderDate

答案 2 :(得分:0)

如果你想删除重复使用联合

 select ID, Percentage, OrderDate
 from table1
 union
 select ID, Percentage, OrderDate
 from table2

如果您希望表中的所有行都使用union all

 select ID, Percentage, OrderDate
 from table1
 union all
 select ID, Percentage, OrderDate
 from table2