SQL Server CTE 结果基于多个列



我有一个这样的CTE:

with cte as
(
-- beep boop beep
) 
select * 
from cte 
where rowNum = 1

返回例如 6 列:

a | b | c |   d   | e  | f
---+---+---+-------+----+---
1 | i | 0 |  qwe  | :/ | r 
1 | j | 2 |  asd  | :) | r 
1 | k | 4 |  zxc  | :( | r
2 | i | 0 |  qwe  | :D | r 

我还有另一个表可以用作其中一些结果的组合键:

a | c |  d
---+---+-----
1 | 2 | asd
2 | 0 | qwe

有没有办法使用第二个表从结果集中排除第 2 行和第 4 行,而无需更改括号内的 CTE?

起初我想加入排除表上的 CTE,但语法说no- 然后我试图使用where子句来排除结果,但实际上我不知道如何在多列上排除。

只需使用not exists

select cte.*
from cte
where rownum = 1 and
not exists (select 1
from exclusions e
where e.a = cte.a and e.c = cte.c and e.d = cte.d
);

强烈建议使用子查询NOT EXISTS而不是NOT IN。 如果NULL任何返回值,则NOT IN的行为不符合预期。 我最好的建议是避免使用它,习惯NOT EXISTS,这样您将来就不会遇到意外问题。

您可以使用不在条件中,

with cte as
(
) 
select * from cte where (a,c,d) not in 
(select a,c,d from table2);

最新更新