假设有这样一个实例:
create table a(dept_id int, user_id int)
insert into a select 1, 1
insert into a select 1, 2
insert into a select 1, 13
insert into a select 1, 4
insert into a select 2, 4
insert into a select 2, 1
insert into a select 2, 13
insert into a select 3, 1
insert into a select 3, 10
insert into a select 3, 4
select * from a
表a记录着dept和user的关系,2个dept中只要有2个以上的相同user,那么我们就认为这2个dept有关联,把这样的dept找出来,返回:
dept_id dept_id
1 2
1 3
2 3
(注意只保留一种对应情况,剔除掉重复情况)
实际案例:
通过人员比较来确定单位是否相同
其中只要有三个以上相同的人员,我们就认为是同一个单位了
SQL如下,注意这里使用"
select x.dept_id as aa, y.dept_id as bb
from a x, a y
where x.user_id = y.user_id and x.dept_id < y.dept_id
group by x.dept_id, y.dept_id
having count(*) >= 2
order by aa
可以和以下SQL比较:
select x.dept_id as aa, y.dept_id as bb
from a x, a y
where x.user_id = y.user_id and x.dept_id <> y.dept_id
group by x.dept_id, y.dept_id
having count(*) >= 2
order by aa
第一条SQL只取x中dept_id小于y中dept_id的记录,过滤了重复记录!很巧妙。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/66009/viewspace-881832/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/66009/viewspace-881832/