Reputation: 1
I have a table and i want to produce a Cartesian of that data with same table itself.
TABLE: TEMP_TEST
FROM_COL
--------------
A
B
C
If I write the below query for Cartesian then I get the output
SELECT A.FROM_COL FROM_COL1,
B.FROM_COL FROM_COL2
FROM TEMP_TEST A,
TEMP_TEST B
WHERE A.FROM_COL!=B.FROM_COL ;
output
FROM_COL1 FROM_COL2
A B
A C
B A
B C
C A
C B
But if A to B is present i don't want B to A. How I can I write a query for that?
I need the below output
FROM_COL1 FROM_COL2
A B
A C
B C
Upvotes: 0
Views: 3010
Reputation: 23588
You were very close. Just change your !=
into <
:
with temp_test as (select 'A' from_col from dual union all
select 'B' from_col from dual union all
select 'C' from_col from dual)
select a.from_col from_col1,
b.from_col from_col2
from temp_test a,
temp_test b
where a.from_col < b.from_col;
FROM_COL1 FROM_COL2
--------- ---------
A B
A C
B C
It would be better (ie. more readable/industry standard) if you rewrote the query using ANSI join syntax, though:
select a.from_col from_col1,
b.from_col from_col2
from temp_test a
inner join temp_test b on (a.from_col < b.from_col);
Upvotes: 3