日期:2014-05-17  浏览次数:20385 次

想对分组以后的结果查询,有知道的吗
        单位    值
1 a企业 1
4 a企业 2
6 a企业 1
7 a企业 4
5 b企业 1
2 b企业 2
3 c企业 3

想查询上述表中值 有1有2 但没有 4 的单位 用sql语句怎么实现
sql

------解决方案--------------------

select 单位 from 表 where 值 in (1,2)
except
select 单位 from 表 where 值=4

------解决方案--------------------
;with cte(id,unit,value) as
(
select 1,'a企业',1
union all select 4,'a企业',2
union all select 6,'a企业',1
union all select 7,'a企业',4
union all select 5,'b企业',1
union all select 2,'b企业',2
union all select 3,'c企业',3
)

select *
from cte a
where  unit not in(select unit from cte b where value in(1,2,4))

/*
id unit value
3 c企业 3
*/

------解决方案--------------------
select * from (
select *
from 
(select distinct 单位 from t) a
full join (select distinct 值 from t) b
) a
left join t b on a.单位=b.单位 and a.值=b.值
where a.值=4 and b.单位 is null