【问题标题】:I have 2 date fields and I want records that fall into 1 or both我有 2 个日期字段,我想要属于 1 或两者的记录
【发布时间】:2013-03-28 21:03:19
【问题描述】:

我有 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。我似乎无法让它工作,感谢任何帮助,谢谢!

【问题讨论】:

  • 当你说你不能让它工作时,你是什么意思?您收到错误消息、错误数据还是什么?
  • 另外,您使用的是什么 RDMS?
  • oracle 10,我没有收到错误消息,但我收到了不正确的数据。我只得到 customer_records.join_date 而不是它的完整列表。

标签: sql date where


【解决方案1】:
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'))

【讨论】:

  • 刚刚看到上面的 cmets - 这些信息会有很大帮助。但是,我猜您只有在发生拒绝的情况下才有拒绝记录,因此常规连接只会匹配那些被拒绝的记录。左连接(这是 MS-SQL 语法)将包括所有记录,如果拒绝表中没有匹配项,则拒绝日期为 NULL。您还应该为您的表格设置别名(例如 cr 而不是 customer_records),因为这样更容易理解。
  • 嗨 Chris K,我想我需要为您提供更多信息。当我执行您的建议时,我收到一个错误:OR 或 IN 的操作数中不允许外连接运算符 (+)。我不知道外连接会影响这种情况,因为我认为这只是我的逻辑错误。我更新了代码以反映外部连接。
【解决方案2】:

当你说你似乎无法让它工作时,我认为你运行了查询并且你没有得到预期的结果并且你没有得到任何错误。 有时,一些日期字段与时间分数一起存储在数据库中。所以你需要使用“trunc”功能。请参阅 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')
      )

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

【讨论】:

  • 好的,我试试这个,谢谢。 (我会立即回复,但我必须出去开会)。
  • 截断没有改变任何东西。
  • 请从您的表格中发布一些示例行,并说出您希望从示例行中获得什么。这将使我们能够更好地了解您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多