2

I have a problem that I need to identify how many companies participated in a given project number. For example, identify which companies participated in exactly 2 projects.

Given the base below:

id company project  
1 company1 project1
2 company2 project1
3 company3 project2
4 company1 project2
5 company2 project2
6 company2 project3
7 company3 project1
8 company1 project1
9 company2 project2
10 company1 project2

How to use a SQL query to solve this problem? For this case above, the query is expected to return:

company1
company2

2 Answers 2

3

You can use aggregate by company and filter with a having clause:

select company
from mytable
group by company
having count(project) = 2

If the same project may occur twice for a given company, then you want count(distinct project) instead of count(project).

Sign up to request clarification or add additional context in comments.

Comments

2

You use group by and having:

select company
from t
group by company
having count(distinct project) = 2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.