各位:
   有一销售表tab_sales,字段为:
     timeid      销售月份,如200701
     customerid  业务员编号
     sales       销售金额
   
   
   要求结果如下:
    找出当月的前一月及后一月的销售金额,满足条件是销售额非空.
    即找出离本月最近的有销售额的前一月及最近的后一月的销售.如,当前月份为0701, 
   往前找,如果最近的0612月份销售为空,0611销售为100,     
   则取0611月份销售100;
   往后找,如果最近的0702月份销售为空,而0703月份有销售为120,
   则取0703月份销售120.请问,如何通过ORACLE分析函数实现此功能.注: 因为数据量较大,在40万条左右. 所以使用游标一行一行求出,速度太  慢.因此,想通过使用ORACLE分析函数实现此功能.

解决方案 »

  1.   

    如果每个月销售额为0就没有纪录,可以这样做
    select 
    from table_sales a,
    (select a.customerid,max(a. timeid )
    from table_sales a
    where timeid<to_date('200709','yyyymm')
    group a.customerid) p_month,
    select a.customerid,min(a. timeid )
    from table_sales a
    where timeid>to_date('200709','yyyymm')
    group a.customerid) n_month,
    where
    a.customerid=p_month.customerid(+)
    and a.customerid=n_month.customerid(+)这个语句没测试过,不知道正确度
      

  2.   

    我测试是成功的,你试试看~~~SQL> select * from tab_sales tt;TIMEID CUSTOMERID      SALES
    ------ ---------- ----------
    200701 0010              200
    200611 0020              600
    200611 0030              300
    200702 0040              200
    200702 0050              200
    200703 0060              400
    200703 0070              200
    200703 0080              700
    200703 0090              2009 rows selectedSQL> 
    SQL> select decode(sum(case when tt.timeid = to_char(add_months(to_date('200701','yyyymm'),-1),'yyyymm') then tt.sales else 0 end),0,sum(case when tt.timeid = to_char(add_months(to_date('200701','yyyymm'),-2),'yyyymm') then tt.sales else 0 end),sum(case when tt.timeid = to_char(add_months(to_date('200701','yyyymm'),-1),'yyyymm') then tt.sales else 0 end)) as "Front Month",
      2         decode(sum(case when tt.timeid = to_char(add_months(to_date('200701','yyyymm'),1),'yyyymm') then tt.sales else 0 end),0,sum(case when tt.timeid = to_char(add_months(to_date('200701','yyyymm'),2),'yyyymm') then tt.sales else 0 end),sum(case when tt.timeid = to_char(add_months(to_date('200701','yyyymm'),1),'yyyymm') then tt.sales else 0 end)) as "After Month"
      3    from tab_sales tt;Front Month After Month
    ----------- -----------
            900         400SQL> 如果时间是今天,把to_date('200701','yyyymm')改成sysdate就好了。
      

  3.   

    取出按照月份group by 的金额,和rownum,按照月份排序,
    除去合计金额等于0的数据。利用LAG函数,LEAD函数,可以取得。