Skip to content
Advertisement

Count nested records in SQL query

I have a problem that I need to select all owners who have 2 different companies where each company is on 2 different projects.

For example :

I tried to do like this :

But it did not work.

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

Advertisement

Answer

I have a problem that I need to select all owners who have 2 different companies where each company is on 2 different projects.

Use two levels of aggregation:

This assumes that owner/company/projects are not duplicated. If that is possible, use count(distinct project) in the subquery.

Note: If you mean owners that have at least two companies with at least two projects, then you would tweak this to:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement