在T-SQL中,如何从另一个select语句的结果中过滤列值?在这个例子中,我想选择一个'从tb2开始,因为tb1的结果是' a'并且' e。
更新:澄清我的问题,因为它引起了一些混乱。还添加了示例所需的结果。
示例:
select * from (select 'a' as C1 union select 'e' as C1) as tb1
select * from (select 'a b c' as col1
union select 'd e f' as col1
union select 'a e f' as col1) as tb2
============
co1
a b c
d e f
a e f
============
c1
a
e
仅过滤后' e f'留下因为它既有' a'和'
============
c1
a e f
这是可能的where子句,还是我必须创建表来以某种方式索引它?
更新:尝试了第一个答案,但没有得到我预期的结果。
select c1 into #tb1 from (select 'a b c' as c1
union select 'd e f' as col1
union select 'a e f' as col1)
as tb1
select col1 into #tb2 from (select 'a' as col1 union select 'e' as C1) as tb2
select t1.c1, t2.col1 from #tb1 as t1
left join #tb2 as t2 on t1.c1 like '%' + t2.col1 + '%'
where t2.col1 is null
============
c1 col1
a b c a
a e f a
a e f e
d e f e
答案 0 :(得分:1)
试试这个:
select a.C1
from tb1 t1
left join tb2 t2
on t1.C1 like '%' + b.col1 + '%'
where b.col1 is null
e.g
============ ============
C1 col1
============ ============
abc b
adc e
aec ============
============
结果将是
============
C1
============
adc
更新:
你想要那些有col1的C1记录:
select distinct a.C1
from tb1 t1
join tb2 t2
on t1.C1 like '%' + b.col1 + '%'
关于查询的一些提示:
你可以看到我删除了where语句并将左连接更改为内连接(join是默认为内连接)。所以它会过滤掉在tb1的C1中没有t2的col1的记录。如果您给出了类似的' abc',' aef'' def' t1,' a',' e' T2。你有两个' a'并且' e' in' aef'所以加入会给'aef'两次。使用distinct来使它只有1条记录。