外连接 - oracle

时间:2012-02-10 16:25:49

标签: sql oracle oracle10g

我有2张桌子

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

有办法做到这一点吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

常见的Oracle语法

选择一个。*,b.spent'上一个已发送' 来自current_expense a,previous_expense b 其中a.type = b.type

或标准中的相同内容

选择一个。*,b.spent'上一个已发送' 来自current_expense作为 内部联接previous_expense为a.type = b.type

上的b

答案 2 :(得分:0)

我倾向于用SQL92编写(更多SQLness而不是Oracle-ness) 这是我的答案:

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;