如何基于日期

时间:2016-08-21 10:25:45

标签: sql oracle

我有两张桌子。 第一张表如下所示

    session_start_dt  |  package_key
-------------------------------------------
   01-01-2015        |  202
   01-02-2015        |  203
   01-14-2016        |  204
   12-01-2015        |  206
   03-02-2015        |  204
   04-14-2016        |  202

第二张表如下所示

package_key     |  term_start_date    |   term_end_date  | Active | event
 202             |  01-01-2014         |   01-01-2015     | Y     | NS
 202             |  01-01-2014         |   01-01-2015     | Y     | CAN
 203             |  01-02-2015         |   01-02-2016     | N     | NS
 204             |  01-02-2015         |   01-02-2016     | N     | NS
 206             |  01-02-2015         |   01-02-2016     | N     | NS
 206             |  01-01-2014         |   01-01-2015     | Y     | NS

当session_start_dt介于第二个表的term_start_date和term_end_date之间时,我需要从第一个表中获取所有记录并从第二个表中获取它是否处于活动状态。

session_start_dt   |  package_key | Active
-------------------------------------------
 01-01-2015        |  202         |  Y
 01-02-2015        |  203         |  N
 01-14-2016        |  204         |  null
 12-01-2015        |  206         |  N
 03-02-2015        |  204         |  N
 04-14-2016        |  202         |  null

我正在编写像

这样的查询
select package_key, session_start_dt from table a, table b 
where SESSION_START_Dt BETWEEN TERM_START_DATE AND TERM_END_DATE AND 
PACKAGE_KEY = PACKAGE_KEY and event not in ('CAN') 

并且它没有给出期望的结果。

1 个答案:

答案 0 :(得分:1)

您可以将between用于join条件。我认为这是你想要的逻辑:

select t1.*, t2.active
from table1 t1 left join
     table2 t2
     on t1.package_key = t2.package_key and
        t1.session_start_dt between t2.term_start_date and t2.term_end_date;