我有2个日期字段,我想要记录为1或两者

时间:2013-03-28 21:03:19

标签: sql date where

我有2个日期字段,我试图在where子句中使用OR。例如,

Select customer_records.customer_id, customer_records.join_date, rejected_customers.rejected_date, status_lookup.status_description 
From customer_records, rejected_customers, status_lookup
Where status_lookup.status_id(+) = customer_records.status_id and customer_records.customer_id = rejected_customers.customer_id
and (customer_records.join_date between to_date('01-10-2012','dd-mm-yyyy') and to_date('01-11-2012','dd-mm-yyyy') or rejected_customers.rejected_date between to_date('01-10-2012','dd-mm-yyyy') and to_date('01-11-2012','dd-mm-yyyy')

所以,基本结果应该是,当加入日期或拒绝日期落入我的日期字段时,我想要customer_id。我似乎无法让它工作,任何帮助表示赞赏,谢谢!

2 个答案:

答案 0 :(得分:0)

Select cr.customer_id, cr.join_date, rej.rejected_date
from customer_records cr left join rejected_customers rej on cr.customer_id=reg.customer_id
where (cr.join_date between to_date('01-10-2012','dd-mm-yyyy') and to_date('01-11-2012','dd-mm-yyyy')) or (rej.rejected_date between to_date('01-10-2012','dd-mm-yyyy') and to_date('01-11-2012','dd-mm-yyyy'))

答案 1 :(得分:0)

当你说你似乎无法让它工作时,我认为你运行查询而你没有得到预期的结果,你没有得到任何错误。 有时,某些日期字段以时间分数存储在数据库中。所以你需要使用“截断”功能。请参阅Oracle数据库中的此示例:

SQL> select to_char(sysdate,  'dd/mm/yyyy hh:mi:ss') date_no_trunc from dual;

DATE_NO_TRUNC
-------------------
28/03/2013 10:04:27

SQL> select to_char(trunc(sysdate),  'dd/mm/yyyy hh:mi:ss') date_with_trunc from dual;

DATE_WITH_TRUNC
-------------------
28/03/2013 12:00:00

SQL> 

因此您需要将查询更改为:

Select c.customer_id,
       c.join_date,
       r.rejected_date
From   customer_records c,
       rejected_customers r
Where  c.customer_id = r.customer_id
and   ( trunc(c.join_date) between to_date('01-10-2012','dd-mm-yyyy') and to_date('01-11-2012','dd-mm-yyyy')
        or
        trunc(r.rejected_date) between to_date('01-10-2012','dd-mm-yyyy') and to_date('01-11-2012','dd-mm-yyyy')
      )

此外,给长表名称别名总是一个好主意,这会使您的查询更短并且使用更少的内存。