Search code examples
sqloracle-databasecross-join

Oracle Cross join


I've got these three tables.

Table1:

Resource1
Resource2
Resource3

Table2:

Period1
Period2
Period3

Table3:

Resource1 Period1
Resource1 Period2
Resource1 Period2
Resource2 Period1
Resource2 Period1
Resource3 Period3

I need to get this result:

Resource1 Period1
Resource1 Period2
Resource1 Period2
Resource1 Period3
Resource2 Period1
Resource2 Period1
Resource2 Period2
Resource2 Period3
Resource3 Period3
Resource3 Period1
Resource3 Period2

I tried outer joins but no effect. I have found that probably cross join should help but I was not successfull in implementing it. Could be someone so kind and help me with this stuff?

Thank you very much, r.


Solution

  • use a common table expression to generate all the combinations, then use an outer join to include the duplicates shown in table3.

    with cte as ( select resource, period
                  from table1 cross join table2 )
    select cte.resource
           , cte.period
    from cte
         left outer join table3
              on (table3.resource = cte.resource
                 and table3.period = cte.period ) 
    ;
    

    This may not produce the right answer, depending on what you mean by " I don't know how to get rid of unneccessary rows ". The output you present doesn't appear to discard any rows from the tables and you haven't provided any rules. So, if this doesn't give you what you want you must edit your question to clarify matters.