繁体   English   中英

外部联接-Oracle

[英]Outer join - oracle

我有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

有没有办法做到这一点?

尝试:

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

通用Oracle语法

从current_expense a,previous_expense b中选择a。*,b。花费'previous Sent',其中a.type = b.type

或标准中的同一件事

从current_expense中选择a。*,b.spent'previous Sent'作为内部联接,previous_expense作为a.type = b.type上的b

我倾向于用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM