I have a list of projects, and different companies bidding for those projects.
project_name company_name
___________________________
abc | 1
abc | 2
abc | 3
def | 9
def | 7
ghi | 8
jkl | 1
jkl | 5
jkl | 6
jkl | 7
I want to keep only the projects where company "1" is present, while also keeping the other competitors for the project. The desired result is:
project_name company_name
___________________________
abc | 1
abc | 2
abc | 3
jkl | 1
jkl | 5
jkl | 6
jkl | 7
I have a feeling a subquery after WHERE is required to get that result, but I can't figure it out.
You can use exists
:
select p.*
from projects p
where exists (select 1
from projects p2
where p2.project_name = p.project_name and
p2.company_name = 1
);
Another option is window functions , often more efficient as it only requires one scan of the table. We can use a conditional count here:
select p.*
from (
select *,
count(case when company_name = 1 then 1 end) over (partition by project_name) hasCompany1
from projects
) p
where hasCompany1 > 0;
This is the simplest query should work for this case:
select p.*
from projects p
where p.project_name in (select project_name from projects where company_name = 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.