替代SQL Server中的所有";(";除外)
标准SQL定义EXCEPT ALL
,其操作如下(Postgres fiddle)
CREATE TABLE T1(X INT);
CREATE TABLE T2(X INT);
INSERT INTO T1 VALUES (1),(1),(2);
INSERT INTO T2 VALUES (1),(2);
SELECT X
FROM T1
EXCEPT ALL
SELECT X
FROM T2
这将返回
+---+
| X |
+---+
| 1 |
+---+
因为T1
vsT2
中有额外的1
行。
SQL Server仅允许EXCEPT
和
SELECT X
FROM T1
EXCEPT
SELECT X
FROM T2
返回空的结果集。如何实现EXCEPT ALL
?
解决方案
EXCEPT ALL
不受SQL Server支持。使用表格
t1 a | b --+-- 1 | 1 1 | 1 1 | 1 1 | 2 1 | 2 1 | 3
和
t2 a | b --+-- 1 | 1 1 | 2 1 | 4
查询
select a, b from t1
except all
select a, b from t2
order by a, b;
将返回
a | b --+-- 1 | 1 1 | 1 1 | 2 1 | 3
因为T1比T2多包含两(1|1)行、多(1|2)行和(1|3)行。
要在SQL Server中实现同样的功能,请对行进行编号:
select a, b from
(
select a, b, row_number() over (partition by a, b order by a) as rn from t1
except
select a, b, row_number() over (partition by a, b order by a) as rn from t2
) evaluated
order by a, b;
相关文章