如何在另一个加入后加入一个表?

时间:2011-04-20 10:27:28

标签: sql join

你好,我试图在另一个连接表之后加入表。我的预期输出是让CODE1,CODE2和CODE3中的所有代码都如下表所示:

channel_division_group staff_id the_code total update_dt
---------------------- -------- -------- ----- ---------
CH3                    101      CODE1    1     03-Mar-11
CH3                    101      CODE1    1     03-Mar-11
CH3                    101      CODE2    1     03-Mar-11
CH3                    101      CODE3    1     03-Mar-11

但实际结果是缺少CODE3的行:

channel_division_group staff_id the_code total update_dt
---------------------- -------- -------- ----- ---------
CH3                    101      CODE1    1     03-Mar-11
CH3                    101      CODE1    1     03-Mar-11
CH3                    101      CODE2    1     03-Mar-11

以下是供您参考的源代码:

    select channel_division_group, staff_id, the_code, total, update_dt
    from (
        select 'CODE1' the_code from dual
        union all
        select 'CODE2' the_code from dual
        union all
        select 'CODE3' the_code from dual
    )
    left outer join (
        select a.staff_id, a.code, update_dt, 
            case when m.update_dt is null then 0
                      else count(*)
            end total,
            case a.channel_division_group
                when 'CH1' then 'CH1'
                when 'CH2' then 'CH2'
                else 'CH3'
            end tableC
        from (
            select code, staff.staff_id, staff.channel_division_group
            from (
                select 'CODE1' code, '1' seq from dual
                union all
                select 'CODE2' code, '2' seq from dual
                union all
                select 'CODE3' code, '3' seq from dual
            ), code_staff staff
        ) a
        left outer join tableM m
        on a.code = m.decision and to_char(a.staff_id)=m.approval_id
        group by a.staff_id, a.code, update_dt, a.channel_division_group
        order by a.channel_division_group, a.staff_id
    ) app
    on the_code=app.code and staff_id=app.staff_id
    where update_dt between trunc(to_date('13-MAR-11'), 'MONTH') and trunc(to_date('13-MAR-11'))
    group by channel_division_group, staff_id, the_code, total, update_dt
    order by staff_id;

如果删除where子句语句,将显示CODE3,但不会在日期内过滤。当一个又一个的连接与where子句一起连接时,这可以完成吗?

谢谢@!

1 个答案:

答案 0 :(得分:1)

你去复杂加入更好地使用“with statement”进行sql join,如下所示。

with
   temp_t1 as (
               select dummy c1 from dual
              )
  ,temp_t2 as (
               select dummy c1 from dual
              )
select *
from temp_t1 a
    ,temp_t2 b

它帮助你。