加入至少有一个参数的比赛

时间:2012-11-18 17:45:44

标签: sql oracle join

我有两张桌子:

T1(RES1, RES2)
T2(RES, WORD, COUNT)

我需要生成T3:

T3(RES1, RES2, WORD, COUNT)

如以下示例所示

T1
RES1   RES2
------------
A      B
C      D

T2
RES    WORD     COUNT
----------------------
A      W1        10
B      W1        5
B      W2        7
C      W2        8

T3
RES1   RES2      WORD  COUNT
-----------------------------
A       B         W1     15 = (10+5)
A       B         W2     7  = (NOTHING FOR A+7)
C       D         W2     8  = (8+NOTHING FOR D)

也就是说,对于T1中的每一对,生成与其一起出现的不同字数。在SQL中执行此操作的最有效方法是什么?

1 个答案:

答案 0 :(得分:2)

-- sample of data from your question
SQL> with t1(RES1, RES2) as(
  2    select 'A', 'B'  from dual union all
  3    select 'C', 'D'  from dual
  4  ),
  5  t2(RES , WORD,     COUNT1) as(
  6    select 'A',  'W1',   10 from dual union all
  7    select 'B',  'W1',    5 from dual union all
  8    select 'B',  'W2',    7 from dual union all
  9    select 'C',  'W2',    8 from dual
 10  ) -- the query
 11  select t1.res1
 12       , t1.res2
 13       , t2.word
 14       , sum(t2.count1) as count
 15    from t1
 16    join t2
 17      on (t1.res1 = t2.res or
 18          t1.res2 = t2.res)
 19  group by t1.res1
 20         , t1.res2
 21         , t2.word
 22  order by t1.res1
 23  ;

RES1 RES2 WORD      COUNT
---- ---- ---- ----------
A    B    W1           15
A    B    W2            7
C    D    W2            8