2012-02-10 78 views
0

我有2個tabels外連接 - 甲骨文

Current Ecpense table 
----------------------- 

Month-----Type-------spent 
Feb 12 Shopping 100 
Feb 12 Food  200 
Jan 12 Shopping 456 
Jan 12 Food  452 
Jan 12 Fuel  120 
Jan 12 Rent  900 

Previous Expense 
----------------------- 
Type------ spent 
Shopping 100 
Food  100 
Fuel  100 
Rent  100 

現在我想加入這兩個表,該預期的結果;

Month-----Type-------spent-----Previous Spent 
Feb 12 Shopping 100  100 
Feb 12 Food  200  100 
Feb 12 Fuel  0  100 
Feb 12 Rent  0  100 
Jan 12 Shopping 456  100 
Jan 12 Food  452  100 
Jan 12 Fuel  120  100 
Jan 12 Rent  900  100 

有沒有辦法做到這一點?

+0

我不明白「以前的費用」表的含義。 'type'是它的主鍵嗎? (例如,那張桌子上只有一個「購物」記錄?) – ruakh 2012-02-10 16:30:01

+2

順便說一下,您之前在這裏提出過幾個問題,對於其中大部分問題,您都沒有接受任何答案。如果你找到答案有幫助,那麼你應該接受他們;如果你還沒有,那麼你應該重新檢查你的問題,看看你能否弄清楚爲什麼他們沒有得到有用的答案。也許你的問題不包含關於你的問題的足夠信息? – ruakh 2012-02-10 16:32:26

回答

0

嘗試:

select m.month, 
     p.type, 
     coalesce(c.spent,0) spent, 
     p.spent previous_spent 
from (select distinct month from current_expense) m 
cross join previous_expense p 
left join current_expense c 
     on m.month = c.month and p.type = c.type 
0

常見的Oracle語法

選擇*,b.spent '以前已發郵件' 從current_expense一個 ,previous_expense b 其中a.type = b.type

或標準中的同一事物

從current_expe中選擇a。*,b.spent'上次發送' NSE作爲 內部聯接previous_expense爲b上a.type = b.type

+0

問題的標題在這裏有一個提示... – 2012-02-10 16:41:11

0

我傾向於在S​​QL92(更多SQLness少甲骨文岬)
這裏寫的是我的回答:

select 
    z.month  as month   , 
    z.type   as type   , 
    nvl(c.spent,0) as spent   , 
    nvl(p.spent,0) as previous_spent 
from 
    (select 
     x.month as month , 
     y.type as type 
    from 
     (select distinct month 
     from current_expense) x 
     cross join 
      (select distinct type 
      from current_expense) y) z 
    left outer join current_expense c 
    on z.month = c.month and 
     z.type = z.type 
    left outer join previous_expense p 
    on z.type = p.type;