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);
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)
/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With