替代SQL Server中的所有"("除外)

2022-08-24 00:00:00 sql tsql sql-server hana sap

标准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 |
+---+

因为T1vsT2中有额外的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;

相关文章