日期:2014-05-19  浏览次数:20560 次

SELECT 条件问题2
如下,表1和表2的OIid对应:
表1
Did                     OIid
10                             1
12                             3
13                             10
表2
OIid                   Ostatus
1                             -1
1                             -1
2                               -1
2                               0
3                               0
3                               -1
3                               2
从以上2个表中选择结果
Did                        
10
因为只有Did为10的其Ostatus   全部为-1,高手来解

------解决方案--------------------
select did from 表1 where OIid in (select OIid from 表2 where Ostatus=-1 group by OIid,Ostatus having count(1)=1)
------解决方案--------------------
select Did from 表1 where OIid in(select OIid from 表2 group by OIid having abs(sum(ostatus))=count(1))
------解决方案--------------------
select Did from @tb2 as tb2 left join @tb1 as tb1
on tb1.OIid=tb2.OIid
group by Did,tb2.OIid
having sum(case Ostatus when -1 then 1 else 0 end)=count(Ostatus)
------解决方案--------------------
create table a(Did int,oIid int)
go
create table b(oIid int ,ostatus char(2))
go
insert into a select 10 ,1 union all
select 12 ,3 union all
select 13 ,10
go
insert into b select 1 ,-1 union all
select 1 ,-1 union all
select 2 ,-1 union all
select 2 , 0 union all
select 3 ,0 union all
select 3 ,-1 union all
select 3 ,2
go

select a.Did from a ,b where a.oIid = b.oIid group by a.Did
having sum(case b.ostatus when -1 then 1 else 0 end ) = count(b.ostatus)

drop table a
drop table b