使用connect和level by的SQL外连接

时间:2013-04-27 22:05:47

标签: oracle oracle10g oracle11g

在几个表上进行SQL连接,以便在特定条件下维护记录

表格 -

PID     Date        COL-A   COL-B
11      01-APR-13   AA      BE
11      03-APR-13   DD      BE
22      03-APR-13   EW      BD
33      01-JUN-13   AR      B7
11      20-APR-13   AS      AS

表格B

PID     Date        COL-A   COL-B
11      01-APR-13   AT      BW
22      04-APR-13   AG      BD
11      07-APR-13   AD      BW
33      08-MAY-13   AG      BF

表格 - C

PID     Date        COL-A   COL-B
11      01-APR-13   AG      BR
22      02-APR-13   AR      B3
33      03-APR-13   A3      BY
44      01-APR-13   AB      BY

查询#带有记录的表至少有Y或N,如果其中一个表的记录与(11,22)中的PID和01-APR-13和07-APR-13之间的日期范围< / p>

输出类似于

PID     Date            Table - A       Table - B       Table - C
11      01-APR-13       Y               Y               Y
22      02-APR-13       N               N               Y
11      03-APR-13       Y               N               N
22      03-APR-13       Y               N               N
11      07-apr-13       N               Y               N

我知道我可以加入表格,但我想我可以扫描日期范围吗?我想我可以使用等级并从oracle 11g连接以获得日期范围。

更新#我需要在这种性质中组合几个表,以获得每个表的相应Y和N值。话虽如此,我不确定Union是否是一个不错的选择。

1 个答案:

答案 0 :(得分:0)

您不需要一系列日期,实际上您需要一个pid列表。如果你有3个表格,我希望你有第四个“主”列表,所有这些都有外键。没有你必须自己创建该列表。创建日期列表只是意味着您有很多日期缺少其他信息。

您的完整查询最终会看起来像这样:

with pid_list as (
        -- Generate list of all PID/date combinations
 select pid, date
   from tablea
  union
 select pid, date
   from tableb
  union
 select pid, date
   from tablec
        )
select pl.pid, pl.date
     , case when a.pid is not null then 'Y' else 'N' end as tablea
     , case when b.pid is not null then 'Y' else 'N' end as tableb
     , case when c.pid is not null then 'Y' else 'N' end as tablec 
  from pid_list pl
  left outer join tablea a
    on pl.pid = a.pid
   and pl.date = a.date
  left outer join tableb b
    on pl.pid = b.pid
   and pl.date = b.date
  left outer join tablec
    on pl.pid = c.pid
   and pl.date = c.date
       -- Restrict date ranges from list of PIDs to that required
 where date between to_date('yyyymmdd', '20130401') 
                and to_date('yyyymmdd', '20130407')
       -- Enforce condition that PID must exist in one of the tables
   and exists ( select 1
                  from pid_list
                 where pid in (11, 22)
                   and date between to_date('yyyymmdd', '20130401')
                                and to_date('yyyymmdd', '20130407')
                       )

我假设实际的列名不是DATE,因为这是一个保留字。