简体   繁体   中英

Query to Not selecting columns if multiple

I've been scratching my head about this.

I have a table with multiple columns for the same project. However, each project can have multiple rows of a different type.

I would like to find only projects type O and only if they don't have other types associated with them.

Ex:

Project_Num | Type
1           | O
1           | P
2           | O
3           | P

In the case above, only project 2 should be returned.

Is there a query or a method to filter this information? Any suggestions are welcome.

You can do this using not exists :

select p.*
from projects p
where type = 'O' and
      not exists (select 1
                  from projects p2
                  where p2.project_num = p.project_num and p2.type <> 'O'
                 );

You can also do this using aggregation:

select p.project_num
from projects p
group by p.project_num
having sum(case when p.type = 'O' then 1 else 0 end) > 0 and
       sum(case when p.type <> 'O' then 1 else 0 end) = 0;

If I understand correctly, you want to check that the project has only record for its project number and it has type 'O'. You can use below query to implement this:

;with cte_proj as
(
select Project_Num from YourTable    
group by Project_Num
having count(Project_Num) = 1)
select Project_Num from cte_proj c
inner join YourTable t on c.Project_Num = t.Project_Num
where t.Type = 'O'

Another option (pretty fast)

SELECT p0.*
FROM project p0
  LEFT JOIN project p1 ON (p0.Type<>p1.Type AND p0.Project_Num=p1.Project_Num)
WHERE p0.Type='O' AND p1.Type IS NULL;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM