查询日期回溯2年

时间:2011-09-21 20:40:42

标签: sql oracle plsql

我需要在WHERE子句中添加一对和语句。

我需要从今天开始获取2年的数据。我不确定如何在SQL中编写它。我得到了所有其他东西,所以它在代码的末尾:

FUNCTION summarize_item_search_data (p_obj_code IN VARCHAR2,  p_val2 IN VARCHAR2,
                                                               p_sac IN NUMBER, p_job_type_id   IN NUMBER,
                                                               p_sup IN NUMBER)
  RETURN sys_refcursor
  IS
  stmt     VARCHAR2(4000);
  result_cur   sys_refcursor;  
 BEGIN

    OPEN result_cur FOR

    SELECT DISTINCT jp.id, jp.row_top.mwslin AS mwslin, jp.obj_code, jp.jobload_year, jp.row_top.fiscal_year AS fiscal_year,
                                      val1s.sac, val2s.val2, val1s.val1,
         DECODE( jp.row_top.val1_id, NULL, jp.row_top.nomenclature ,val1s.nomenclature) AS nomenclature, jp.row_top.sup AS sup
        FROM schedules sch, job_plans JP, master_val1 val1s, master_val2 val2s, TABLE(val2s.group_id) (+) ntab, 
                 groups pgds
  WHERE 
-- stmt := stmt || ' AND ''' || p_year || ''' = ntab.fiscal_year(+)';
    (val1s.sac = p_sac OR p_sac IS NULL) AND

    (UPPER(val2s.val2) LIKE UPPER(p_val2) OR p_val2 IS NULL) AND

    (UPPER(jp.obj_code) LIKE UPPER(p_obj_code) OR p_obj_code IS NULL) AND

    (jp.row_top.sup <= p_sup OR p_sup IS NULL) AND

    (jp.row_top.job_type_id = p_job_type_id OR p_job_type_id IS NULL) 

    AND ntab.group_id = pgds.id(+) 
    AND jp.row_top.val1_id = val1s.id(+) 
    AND val1s.val2_id = val2s.id(+)
    AND  jp.jobload_year > 
    AND  fiscal_year > 


  RETURN result_cur;
  END summarize_item_search_data;

2 个答案:

答案 0 :(得分:2)

AND  jp.jobload_year > ADD_MONTHS(CURRENT_DATE, -24)
AND  fiscal_year > ADD_MONTHS(CURRENT_DATE, -24)

我看到这些字段不是日期时间,因此无效。您需要将它们转换为datetime,或转换为整数并仅按年份进行比较。选择第一个选项,您可以尝试:

AND  TO_DATE('1-1-'||jp.jobload_year) > ADD_MONTHS(CURRENT_DATE, -24)
AND  TO_DATE('1-1-'||fiscal_year) > ADD_MONTHS(CURRENT_DATE, -24)

虽然它不是动态。可以等待更好的解决方案。

答案 1 :(得分:1)

@ Shredder的解决方案非常实用,但它并非sargable。即使今天没有适用的索引,设计查询以便他们可以利用将来可能创建的索引也是一种好的做法(假设它没有增加显着的复杂性):

AND jp.jobload_year > TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
AND fiscal_year > TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')