CREATE TABLE table_a ( id INTEGER NOT NULL PRIMARY KEY
, OrderDate DATE NOT NULL DEFAULT '2003-03-15');
CREATE TABLE table_b ( id INTEGER NOT NULL PRIMARY KEY
, OrderDate DATE NOT NULL DEFAULT '2003-04-15');
INSERT INTO table_a(id) VALUES (0),(2),(4),(6),(8),(10),(12),(14),(16),(18),(20);
INSERT INTO table_b(id) VALUES (0),(3),(6),(9),(12),(15),(18),(21);
SELECT COALESCE (a.id, b.id) AS id
FROM (
SELECT DISTINCT id
FROM table_a
WHERE OrderDate >= '2003-03-01' AND OrderDate < '2003-04-01'
) a
FULL OUTER JOIN (
SELECT DISTINCT id
FROM table_b
WHERE OrderDate >= '2003-04-01' AND OrderDate < '2003-05-01'
) b ON b.id = a.id
WHERE a.id IS NULL OR b.id IS NULL
;
注意:我必须发明自己的数据,因为 OP 没有提供任何数据,而且我懒得输入。
更新:原始 UNION 查询(此处使用 table_a/table_b 构造,对于原始数据模型,使用 table_a = table_b = Sales.SalesOrderHeader
)
SELECT a.id, a.OrderDate
FROM table_a as a
WHERE a.OrderDate >= '2003-03-01' AND a.OrderDate < '2003-04-01' -- march only
AND NOT EXISTS (
SELECT * FROM table_b nx
WHERE nx.id = a.id
AND nx.OrderDate >= '2003-04-01' AND nx.OrderDate < '2003-05-01' -- april only
)
UNION ALL
SELECT b.id, b.OrderDate
FROM table_b as b
WHERE b.OrderDate >= '2003-04-01' AND b.OrderDate < '2003-05-01' -- april only
AND NOT EXISTS (
SELECT * FROM table_a nx
WHERE nx.id = b.id
AND nx.OrderDate >= '2003-03-01' AND nx.OrderDate < '2003-04-01' -- march only
)
ORDER BY OrderDate ASC;
笔记:
UNION
应该是 a ,UNION ALL
因为重复是不可能的,并且不必被删除
- 这些
NOT EXISTS ()
子句是必要的:您想要 3 月份的记录,而 4 月份不存在,反之亦然。
- 需要
UNION
通常表明数据模型次优(在这种情况下不是)
FULL OUTER JOIN
可以认为是关系划分的一种特殊形式