简体   繁体   中英

Oracle how to compare subset in a query

I have one table (T1) with 3 columns: id, category, sector

id, category, sector 
1    1         2 
10   1         3 
10   5         4
20   1         3
20   5         4
20   7         8

I want a query that return the ids with a subset of sector and category of the startig id, that is:

select * from T1 where id=10

return 2 records

The query i'm trying to write should return other ids with the same 2 records even if they have other records. In this example this query should return only the id 20 because is a super set.

Many thanks

Seems you wnat all the rows with category and sectore selected using id 10

select t1.id from t1 
inner join (
  select  category, sector 
  from T1 where id=10 
) t on t.category = t1.category and t.sector = t1.sector

Here is one method:

select t.id
from t join
     (select t2.*, count(*) over (partition by id) as cnt
      from t t2
     ) t2
     on t2.category = t.category and t2.sector = t.sector and
        t2.id = 10
group by t.id
having count(*) = t2.cnt;

It first counts the number of rows for each id. This is important for being sure that you have all of them.

Then, the query does a self-join on category and sector . It aggregates by the first id and counts the matching rows. If all match, then you keep the id .

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