sql查询从现在开始在一行中返回日期为18个月的值

时间:2014-02-04 09:04:32

标签: sql oracle oracle11g

我有一个包含12个句点(月)的表格,如下所述:

CREATE TABLE  "FORECAST_DATA" (
   "COMPANY_CODE" NUMBER(6,0), 
   "CAT" VARCHAR2(30), 
   "PRODUCT_CODE" VARCHAR2(30), 
   "CUSTOMER_CODE" VARCHAR2(30), 
   "CYEAR" VARCHAR2(30), 
   "CHANNEL" VARCHAR2(30), 
   "P_1" NUMBER(6,0), 
   "P_2" NUMBER(6,0), 
   "P_3" NUMBER(6,0), 
   "P_4" NUMBER(6,0), 
   "P_5" NUMBER(6,0), 
   "P_6" NUMBER(6,0), 
   "P_7" NUMBER(6,0), 
   "P_8" NUMBER(6,0), 
   "P_9" NUMBER(6,0), 
   "P_10" NUMBER(6,0), 
   "P_11" NUMBER(6,0), 
   "P_12" NUMBER(6,0), 
   "FORECAST_COST" NUMBER(6,0)
   )

此表用于预测,假设当前日期是2013年2月,我想写一个查询,在一行中返回18个句点(2013年P_2到P_12,2014年P_1到P_7)。

谢谢,

萨贝

2 个答案:

答案 0 :(得分:0)

使用ADD_MONTHS函数可以获得任意数量的列。像这样的东西

SELECT sysdate, 
       ADD_MONTHS(sysdate,1) P_2,
       ADD_MONTHS(sysdate,2) P_3,
       ADD_MONTHS(sysdate,3) P_4,
       ADD_MONTHS(sysdate,4) P_5
FROM   dual;

答案 1 :(得分:0)

function after_current_date(p_months_before number,p_current_month number, p_year number, p_product_code varchar2, p_category varchar2, p_channel varchar2) return number
as
        v_qty number;
        v_quert_stmt  varchar2(4000);
begin

        v_quert_stmt := 'select sum(qty_'||case when p_current_month + p_months_before > 12 
                                                       then case when p_current_month + p_months_before > 24 then
                                                                      p_current_month + p_months_before - 24
                                                                 else p_current_month + p_months_before - 12
                                                            end     
                                                  else p_current_month + p_months_before 
                                             end 
                    ||') from forecast_data_1
                        where cyear        = :bind_year
                         and product_code = :bind_product
                         and cat          = :bind_cat
                         and channel      = case :bind_channel when '||'''%'''||' then channel 
                                                               else :bind_channel end';

    execute immediate v_quert_stmt
    into v_qty
    using case when p_current_month + p_months_before > 12 then case when p_current_month + p_months_before > 24 then p_year + 2
                                                                    else p_year + 1
                                                                end
              else p_year  end,
          P_Product_Code, 
          P_Category,
          p_channel,
          p_channel;

    Return  V_Qty;
end after_current_date;