Til*_*lak 1 sql t-sql sql-server where-clause
考虑表地址,包括字段Country,State和其他数据字段.我希望获得所有记录,除了那些国家,国家组合为(美国,IL),(美国,洛杉矶),(IND,DEL)
查询就像
Select * from Address a
where not exists
(
select Country,State
(select 'US' as Country, 'IL' as State
union
select 'US' as Country, 'LA' as State
union
select 'IND' as Country, 'DEL' as State
) e
where e.Country != a.Country and e.State != a.state
)
Run Code Online (Sandbox Code Playgroud)
如何轻松实现(用简单的子查询替换coutry,state结合)?由于总数据不是很大,我现在对性能最不感兴趣.
我知道我可以创建表变量,使用insert into语法添加所有文字组合,并使用表变量不存在,但我觉得它对于小要求(在2个变量上不存在)是过度的.
看起来您的查询尝试执行此操作:
select *
from Address a
where not exists (
select *
from (
select 'US' as Country, 'IL' as State union all
select 'US' as Country, 'LA' as State union all
select 'IND' as Country, 'DEL' as State
) e
where e.Country = a.Country and
e.State = a.State
)
Run Code Online (Sandbox Code Playgroud)
或者您无法使用派生表并仍然获得相同的结果
select *
from Address as a
where not (
a.Country = 'US' and a.State = 'IL' or
a.Country = 'US' and a.State = 'LA' or
a.Country = 'IND' and a.State = 'DEL'
)
Run Code Online (Sandbox Code Playgroud)
只需直接在查询中使用这些值即可:
-- Sample data.
declare @Table as Table ( Country VarChar(6), State VarChar(6), Foo VarChar(6) );
insert into @Table ( Country, State, Foo ) values
( 'US', 'IL', 'one' ), ( 'XX', 'LA', 'two' ), ( 'IND', 'XXX', 'three' ), ( 'IND', 'DEL', 'four' );
select * from @Table;
-- Demonstrate excluding specific combinations.
select T.*
from @Table as T left outer join
( values ( 'US', 'IL' ), ( 'US', 'LA' ), ( 'IND', 'DEL' ) ) as Exclude( Country, State )
on T.Country = Exclude.Country and T.State = Exclude.State
where Exclude.Country is NULL;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5620 次 |
| 最近记录: |