2012-06-15 45 views
-2

我有5個表:如何針對Oracle編寫此SQL?

TABLE_A: 
    A_ID 

TABLE_B: 
    A_ID 
    B_ID 
TABLE_C: 
    B_ID 
    C_ID 
    C_SOME_NUMBER 

TABLE_D: 
    A_ID 
    D_ID 
TABLE_E: 
    D_ID 
    E_ID 
    E_SOME_NUMBER 

正如你所看到的,映射關係是:

1 A --> n B 
1 B --> n C 
1 A --> n D 
1 D --> n E 

我想寫一個SQL來計算:A_ID的計數:

sum(C_SOME_NUMBER) != sum(E_SOME_NUMBER) 

但我不知道如何寫這個SQL。我的DB是Oracle

+0

@ Fluffeh的解決方案比較,只匹配相同的'A_ID'該款項。如果'TABLE_C'匹配某個'A_ID'而'TABLE_E'沒有,那麼您是否需要'A_ID'來計算? –

回答

2
select 
    count(Q1.ID) as 'whoopsie' 
from 
    (
     select 
      a.ID, 
      sum(c.some_number) as someNum 
     from 
      TA a, 
      TB b, 
      TC c 
     where 
      a.ID=b.IB 
      and b.ID=c.ID 
     group by 
      a.ID 
    ) Q1, 
    (
     select 
      a.ID, 
      sum(e.some_number) as someNum 
     from 
      TA a, 
      TD d, 
      TE e 
     where 
      a.ID=d.IB 
      and d.ID=e.ID 
     group by 
      a.ID 
    ) Q2 
where 
    Q1.ID=Q2.ID 
    and Q1.someNum != Q2.someNum