在请求oracle中按日期选择(之间)

时间:2020-03-06 07:39:57

标签: sql oracle oracle-apex

我编写了一个在apex oracle中使用的查询,在其中添加了过滤器,但是当我添加日期选择时,此查询不起作用(尽管没有语法错误)。我会很感谢您的帮助

select eb.ID,
       eb.NAME,
       eb.TEMP,
       eb.ID_TRANS,
       eb.CR_DATE,
       eb.DATE_TMRT,
       ah.name as Silo_name,
       we.name as ORGANIZATIONS,
       ad.name as item
              from TEMPR_SILO  eb
              left join  ORGANIZATIONS we on  eb.ORGANIZATIONS =  we.id
              left join  ITEM_CRITICALTEMP ad on  ad.id <> 0 
              left join  silo ah  on  ah.id = ad.id_silo 
where   (:P115_ORG is null or we.name = :P115_ORG) 
and (:P115_SILO_NAME is null or  ah.name = :P115_SILO_NAME) 
and  to_timestamp(eb.DATE_TMRT)  between to_timestamp(:P115_DATA1,'dd.mm.yyyy') and to_timestamp(:P115_DATA2,'dd.mm.yyyy') 
------ when "OR" is missing then everything works ---
or   (:P115_DATA2 is null OR :P115_DATA1 is null)
group by
       eb.ID,
       eb.NAME,
       eb.TEMP,
       eb.ID_TRANS,
       eb.CR_DATE,
       eb.DATE_TMRT,
       we.name,
       ah.name,
       ad.name  

但是可能未指定过滤日期,我需要所有记录都可用,因此应该使用“ OP”。如果您能帮助我找到错误,我将不胜感激!

2 个答案:

答案 0 :(得分:0)

我想应该是

where
  (                                                              --> this 
       (:P115_ORG is null or we.name = :P115_ORG) 
   and (:P115_SILO_NAME is null or  ah.name = :P115_SILO_NAME) 
   and  to_timestamp(eb.DATE_TMRT)  between to_timestamp(:P115_DATA1,'dd.mm.yyyy') 
                                        and to_timestamp(:P115_DATA2,'dd.mm.yyyy') 
  )                                                              --> this
  --
  or   (:P115_DATA2 is null OR :P115_DATA1 is null)

即将所有AND条件括在自己的括号中,并将OR条件排除在外。

答案 1 :(得分:0)

假定条件(BETWEEN/NULL)之一为真。
更改以下内容

and  to_timestamp(eb.DATE_TMRT)  between to_timestamp(:P115_DATA1,'dd.mm.yyyy') and to_timestamp(:P115_DATA2,'dd.mm.yyyy') 
------ when "OR" is missing then everything works ---
or   (:P115_DATA2 is null OR :P115_DATA1 is null)

and  (to_timestamp(eb.DATE_TMRT)  between to_timestamp(:P115_DATA1,'dd.mm.yyyy') and to_timestamp(:P115_DATA2,'dd.mm.yyyy') 
------ when "OR" is missing then everything works ---
or   (:P115_DATA2 is null OR :P115_DATA1 is null))

我认为应该可以。

第二种情况:当所有条件或Null条件都为真时:

(
(:P115_ORG is null or we.name = :P115_ORG) 
and (:P115_SILO_NAME is null or  ah.name = :P115_SILO_NAME) 
and  to_timestamp(eb.DATE_TMRT)  between to_timestamp(:P115_DATA1,'dd.mm.yyyy') and to_timestamp(:P115_DATA2,'dd.mm.yyyy')
) 
or   (:P115_DATA2 is null OR :P115_DATA1 is null)