如何在给定日期范围和两个日期范围之间获取记录应该包括搜索记录?

时间:2015-06-15 12:57:45

标签: sql database oracle

以下是查询:

SELECT DECODE(AVSR.INFORMATIONTYPE,'NULL','UNKNOWN','5','Infectious Agent Transmission Issue','4','Environmental Issue','3','Withdrawal Period Issue','2','Lack OF Expected Efficacy','1','Safety Issue') Infotype,
  COUNT(VM.Vaer_No),
  AVSR.INFORMATIONTYPE
FROM AGVET_VAE_INFO VM,
  Agvet_Vae_Safetyreport AVSR
WHERE AVSR.RECORD_ID          = VM.FK_AVSR_REC_ID
AND VM.Vaer_Delete            = 0
AND VM.Archived               = 0
AND VM.E2B_MESSAGE_LIST_TYPE <> 01
AND VM.IMPORT_FLAG           <> 1
AND AVSR.ORIGINALRECEIVEDATE BETWEEN to_date ('2000/04/1', 'yyyy/mm/dd') AND to_date ('2000/04/28', 'yyyy/mm/dd')+1
GROUP BY AVSR.INFORMATIONTYPE 

在此查询中,它还显示记录2000/04/29。但我只需要从2000/04/12000/04/28的记录(包括两个日期)。

3 个答案:

答案 0 :(得分:1)

从第二个日期删除+1

SELECT DECODE(AVSR.INFORMATIONTYPE,'NULL','UNKNOWN','5','Infectious Agent Transmission Issue','4','Environmental Issue','3','Withdrawal Period Issue','2','Lack OF Expected Efficacy','1','Safety Issue') Infotype,
  COUNT(VM.Vaer_No),
  AVSR.INFORMATIONTYPE
FROM AGVET_VAE_INFO VM,
  Agvet_Vae_Safetyreport AVSR
WHERE AVSR.RECORD_ID          = VM.FK_AVSR_REC_ID
AND VM.Vaer_Delete            = 0
AND VM.Archived               = 0
AND VM.E2B_MESSAGE_LIST_TYPE <> 01
AND VM.IMPORT_FLAG           <> 1
AND AVSR.ORIGINALRECEIVEDATE BETWEEN to_date ('2000/04/1', 'yyyy/mm/dd') AND to_date ('2000/04/28', 'yyyy/mm/dd')
GROUP BY AVSR.INFORMATIONTYPE 

答案 1 :(得分:1)

您必须删除+1,因为BETWEEN包含两个限制:

  

expr1 BETWEEN expr2 AND expr3

     

是布尔表达式的值:

     

expr2&lt; = expr1 AND expr1&lt; = expr3

答案 2 :(得分:1)

1)使用trunc

AND trunc(AVSR.ORIGINALRECEIVEDATE) BETWEEN to_date ('2000/04/1', 'yyyy/mm/dd') AND to_date ('2000/04/28', 'yyyy/mm/dd')

但如果列AVSR.ORIGINALRECEIVEDATE上有任何索引,则会忽略它,如果此列上没有索引或者使用函数trunc

有功能索引,则使用它

2)使用>=<

AND (AVSR.ORIGINALRECEIVEDATE >= to_date ('2000/04/1', 'yyyy/mm/dd') AND AVSR.ORIGINALRECEIVEDATE < (to_date ('2000/04/28', 'yyyy/mm/dd') + 1))

3)使用时间戳

AND AVSR.ORIGINALRECEIVEDATE BETWEEN to_date ('2000/04/1 00:00:00', 'yyyy/mm/dd hh24:mi:ss') AND to_date ('2000/04/28 23:59:59', 'yyyy/mm/dd hh24:mi:ss')