计算SQL查询中的嵌套记录

时间:2019-12-18 12:32:32

标签: sql

我有一个问题,我需要选择拥有2个不同公司的所有所有者,而每个公司都在2个不同的项目上。

例如:

owner  company project  
1     company1 project1
1     company1 project2
1     company2 project2
1     company2 project3
1     company2 project1
2     company1 project1
2     company2 project1
2     company3 project1
2     company3 project2
3     company2 project2
3     company1 project1

我试图这样做:

select owner from table 
group by owner 
having count(distinct company)>1 and count(distinct project)>1

但这没用。

如何使用SQL查询解决此问题?对于上述情况,查询将返回:

1

1 个答案:

答案 0 :(得分:3)

  

我有一个问题,我需要选择拥有2个不同公司的所有所有者,而每个公司都在2个不同的项目上。

使用两种聚合级别:

select owner
from (select owner, company, count(*) as num_projects
      from t
      group by owner, company
     ) t
where num_projects = 2
group by owner
having count(*) = 2;

这假定所有者/公司/项目没有重复。如果可能的话,请在子查询中使用count(distinct project)

注意:如果您的意思是拥有至少 两个公司且拥有至少两个项目的所有者,那么您可以将其调整为:

select owner
from (select owner, company, count(*) as num_projects
      from t
      group by owner, company
     ) t
where num_projects >= 2
group by owner
having count(*) >= 2;