Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query items with identical set of values

I'm looking for an efficient way to query items, that have identical set of values.

I have a following table

C_1  C_2
--------
A    1
A    2
-------
B    1
B    2
B    3
-------
C    1
C    2
-------
D    1
D    2
D    3
-------
E    1
E    2 
-------
F    0
F    2 

I will select the list of items FROM C_1 that have exact the same set of c_2 elements as the given item.

For item A i will have

C
E

For item B i will have

D 

how can it be done in SQL( Oracle 10g )?


Here is the create table statement for test purposes

create table t (c_1 varchar2(1), c_2 number);
INSERT into t VALUES('A',    1);
INSERT into t VALUES('A',    2);
INSERT into t VALUES('B',    1);
INSERT into t VALUES('B',    2);
INSERT into t VALUES('B',    3);
INSERT into t VALUES('C',    1);
INSERT into t VALUES('C',    2);
INSERT into t VALUES('D',    1);
INSERT into t VALUES('D',    2);
INSERT into t VALUES('D',    3);
INSERT into t VALUES('E',    1);
INSERT into t VALUES('E',    2); 
INSERT into t VALUES('F',    0);
INSERT into t VALUES('F',    2);
like image 786
schurik Avatar asked Jan 19 '23 11:01

schurik


2 Answers

You can use 10g's COLLECT function; since you don't want to see what the c_2 values are you don't even need to cast it.

select c_1
from t
where c_1 != 'A'
group by c_1
having collect(c_2) = (select collect(c_2) from t where c_1 = 'A' group by c_1)
/
like image 64
Alex Poole Avatar answered Jan 22 '23 00:01

Alex Poole


create type t_c_2 as table of number;

select one.c_1, two.c_1
from (select t.c_1, CAST(COLLECT(t.c_2) as t_c_2) coll
      from t
      group by t.c_1) one
    ,(select t.c_1, CAST(COLLECT(t.c_2) as t_c_2) coll
      from t
      group by t.c_1) two
where one.coll = two.coll
  and one.c_1 != two.c_1;

I've never used such a construction on a production site, efficiency verification is needed.

like image 41
marcink Avatar answered Jan 22 '23 00:01

marcink