【问题标题】:Decode Function解码功能
【发布时间】:2013-08-01 20:47:50
【问题描述】:

我有一个包含三个提示的查询;部门、起始日期和截止日期。必须选择部门 ID,但可以选择日期范围。如何使日期范围可选?我正在考虑使用解码功能,但不知道如何编写,所以两个日期提示可以留空。

【问题讨论】:

  • 信息不足。您应该包括示例数据和可能的预期结果。

标签: sql oracle decode


【解决方案1】:

如果您使用的是存储过程,您可以在 select 语句中执行以下操作:

select *
from table
where (field > inDateStart and field < inDateEnd) or 
      (inDateStart is null and inDateEnd is null)

或使用合并

select *
from table
where (field => coalesce(inDateStart,field) and 
       field <= coalesce(inDateEnd,field) 

这真的取决于你的具体情况。有些查询适用于第一个,有些适用于第二个。

【讨论】:

    【解决方案2】:

    假设未指定的日期输入为 NULL,您可以执行以下小技巧:

    with
     TheTable as
     (select 1 dept, sysdate dt from dual
     union
     select 2 dept, sysdate-63 dt from dual
     union
     select 3 dept, sysdate-95 dt from dual
     )
    select * 
    from thetable
    where coalesce(:DateFrom,dt) <= dt
    and  coalesce(:DateTo,dt) >= dt
    ;
    

    需要更多关于数据性质的信息以将部门视为输入...该表是否为每个部门存储多个日期?

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2011-11-20
      • 2015-08-13
      • 2019-04-02
      • 2015-08-12
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      相关资源
      最近更新 更多