Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

I get your result,but I am not sure whether my thought is right or not..

SELECT A.RESOURCEID,B.PERIOD 
FROM 
TABLE1 A CROSS JOIN TABLE2 B
UNION ALL
SELECT RESOURCEID,PERIOD
FROM TABLE3 C
GROUP BY RESOURCEID,PERIOD
HAVING COUNT(*)>1

http://www.sqlfiddle.com/#!4/36667/2

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top