Home » SQL & PL/SQL » SQL & PL/SQL » Perhaps a stupid query (11.2.0.3)
Perhaps a stupid query [message #628380] |
Mon, 24 November 2014 12:08 |
Amine
Messages: 375 Registered: March 2010
|
Senior Member |
|
|
Hi all,
create table test
(
id int ,
x int
);
insert into test values (1,1);
insert into test values (1,2);
insert into test values (1,3);
insert into test values (1,4);
insert into test values (2,1);
insert into test values (2,2);
insert into test values (2,3);
insert into test values (3,1);
insert into test values (3,2);
I want to get all id that have exactly x in (1,2,3).
In my case the query must return id 2 only.
for all id that have exactly x in (1,2), the query must return id 3 only.
Thanks in advance,
Amine
|
|
|
|
|
|
|
|
|
|
|
|
|
Re: Perhaps a stupid query [message #629398 is a reply to message #629397] |
Mon, 08 December 2014 08:30 |
Amine
Messages: 375 Registered: March 2010
|
Senior Member |
|
|
Now, suppose we add these 2 rows :
insert into test values (4,1);
insert into test values (4,6);
SQL> var txt varchar2(100);
SQL> exec :txt := '1,2';
PL/SQL procedure successfully completed.
SQL>
SQL> select *
2 from
3 (
4 with data
5 as
6 (
7 select
8 trim( substr (txt,
9 instr (txt, ',', 1, level ) + 1,
10 instr (txt, ',', 1, level+1)
11 - instr (txt, ',', 1, level) -1 ) )
12 as token
13 from (select ','||:txt||',' txt
14 from dual)
15 connect by level <=
16 length(:txt)-length(replace(:txt,',',''))+1
17 )
18 select id
19 from test
20 where id in (select id from test where x in (select * from data) )
21 group by id
22 having count(distinct x) = (select count(*) from data)
23 )
24 /
ID
---------
3
4
id 4 should not appear.
|
|
|
Re: Perhaps a stupid query [message #629410 is a reply to message #629398] |
Mon, 08 December 2014 13:14 |
Solomon Yakobson
Messages: 3273 Registered: January 2010 Location: Connecticut, USA
|
Senior Member |
|
|
This time Tom's solution (same as Michel's) isn't correct. Look at:
where id in (select id from test where x in (select * from data) )
It selects any id that has x equal to either 1 or 2. As a result condition
having count(distinct x) = (select count(*) from data)
will be true for all IDs that have x equal to either 1 or 2 and any second value. And if set we are looking for would be 1,2,3 it would return any ID that has 1,2,any or 1,3,any or 2,3,any or 1,any,any or 2,any,any or 3,any,any.
Also Tom's solution doesn't consider NULLs. It will return id even when it has NULL x values in addition set we are looking for.
Anyway, below is collection based solution:
select id
from test
group by id
having set(cast(collect(x) as ku$_objnumset)) = ku$_objnumset(1,2)
/
ID
----------
3
SQL>
And if you don't want to ignore NULLs:
select id
from test
group by id
having set(cast(collect(x) as ku$_objnumset)) = ku$_objnumset(1,2)
and count(*) = count(x)
/
SY.
|
|
|
Goto Forum:
Current Time: Thu Apr 25 18:35:45 CDT 2024
|