sql 简单中的查询,来解决一下...
数据库中某表一字段 A 和 字段 B,数据如下:
A B
a 1
a 2
a 3
b 1
b 2
c 1
c 2
c 3
c 4
我想取出 B字段中所有值为 1和 3对应的值。我要 取 出来的效果是
A B
a 1
a 3
c 1
c 3
怎么写sql语句?
------解决方案--------------------错了,修改下
select * from table1 a where (B=1 or B=3) and
exists(select * from table1 where A=a.A and B=1) and
exists(select * from table1 where A=a.A and B=3)
------解决方案----------------------上面我的錯了,應該是:
declare @t table(A varchar(20),B int)
insert @t select 'a ', 1 union all select
'a ', 2 union all select
'a ', 3 union all select
'b ', 1 union all select
'b ', 2 union all select
'c ', 1 union all select
'c ', 2 union all select
'c ', 3 union all select
'c ', 4
select * from @t a where (B=1 or B=3) and
exists(select top 1 A from @t where A=a.A and B=1) and
exists(select top 1 A from @t where A=a.A and B=3)