Help in Moving Average Query

Hello,
I would like to have a query for finding moving average. based on some conditions.
I have written query as follows:
SELECT Column1,
MONTH_END_DATE,
(AVG(sum(Col2 *(case when (Col3 ='XYZ') then 1 else 0 end)))OVER (PARTITION BY Column1 ORDER BY MONTH_END_DATE ROWS 5 PRECEDING)) AS AVG_XYZ,
sum(Col2 *(case when (Col3 ='XYZ') then 1 else 0 end)) as Cumm_XYZ
FROM
Table_cd
WHERE
Column1 ='1234567'
GROUP BY Column1, MONTH_END_DATE.
My problem is if there are no data in a month, then the average calculated will vary from the required.
For Eg., If i have to find the average of months between JULY and DECEMBER and if the table doesnt have data in the month of OCTOBER, NOVEMBER then while finding the average it will consider only 4 Months instead of 6 Months..So is it possible to write query such that if there are no data in a month then consider the values for that month as zero and then find the average..
If anybody can help me in this regard, it will be very useful

Mr.BluShadow if u can just show me how i can find
average for the values returned by the example
written by you, it would be very helpful..Obviously the hint wasn't enough... here's another...
SQL> ed
Wrote file afiedt.buf
  1  with t as (select to_date('01/07/2007','DD/MM/YYYY') as dt, 1 as val from dual union all
  2             select to_date('02/07/2007','DD/MM/YYYY'), 2 from dual union all
  3             select to_date('03/07/2007','DD/MM/YYYY'), 3 from dual union all
  4             select to_date('04/07/2007','DD/MM/YYYY'), 4 from dual union all
  5             select to_date('01/08/2007','DD/MM/YYYY'), 5 from dual union all
  6             select to_date('02/08/2007','DD/MM/YYYY'), 6 from dual union all
  7             select to_date('03/08/2007','DD/MM/YYYY'), 7 from dual union all
  8             select to_date('01/09/2007','DD/MM/YYYY'), 8 from dual union all
  9             select to_date('02/09/2007','DD/MM/YYYY'), 9 from dual union all
10             select to_date('03/09/2007','DD/MM/YYYY'), 10 from dual union all
11             select to_date('01/12/2007','DD/MM/YYYY'), 11 from dual union all
12             select to_date('02/12/2007','DD/MM/YYYY'), 12 from dual union all
13             select to_date('03/12/2007','DD/MM/YYYY'), 13 from dual union all
14             select to_date('04/12/2007','DD/MM/YYYY'), 14 from dual
15            )
16  --
17  select m.dt, AVG(NVL(t.val,0)) as val
18  from t, (select add_months(to_date('01/07/2007', 'DD/MM/YYYY'),rownum-1) as dt from dual connect by rownum <= 6) m
19  where m.dt = trunc(t.dt(+),'MM')
20  group by m.dt
21* order by dt
SQL> /
DT               VAL
01-JUL-07        2.5
01-AUG-07          6
01-SEP-07          9
01-OCT-07          0
01-NOV-07          0
01-DEC-07       12.5
6 rows selected.
SQL>

Similar Messages

  • Query  for moving average

    Hi ,
    I need query for moving average the same as B1 calculate it.
    Idan

    Hi Idan,
    Moving Average Rate Calculation
    Moving Average Rate = Daily Receipt Value / Daily Receipt Qty
    This Rate generate on daily bases.
    Its called in SAP as Lastevaluated Price
    Thanks,
    Srujal Patel

  • Moving average price query

    Hi Team,
    The Purhcase order is created for 50 qty reference to Contract price 284.58 and we have done the GR for 33 qty on 01 April and invoice completed on 07 april for 33 qty and for the remaning qty 17 we have processed the invoice intially before GR on 18 June and reversed it on 19 June and reprocessed invoice for 17 qty on 26 June also mistankenly one more invoice processed for 8 quantity on 26 June and reveresd on the invoice for 8qty on 14 july and finally we processed the Goods receipt for 17 qty on 15 July and system has picked the Material price as 267.81.
    I know this is an SAP standard behavior for Material with Moving average price,
    The reason for the Goods Receipt Material price value picked by the system as 267.81 is
    INVOICE for 17*284.58 =  4837.86
    INVOICE for 8* 232.18  =  1857.44
                      Total 25     =   6695.3
    Total value (6695.3) / total quantity (25) = 267.81 (Material price)
    Hence when we post the goods receipt system has picked the Material value as 267.81.
    Could you please let me know the reason on the SAP behvaiour below
    we have revered the invoice on 14 July for 8 qty and processed the GR for remaining PO qty 17 only on 15 July eventhough system has picked the Material price as 267.81
    i couldn't able to find the Material price form where system has picked. (it's not update in Material master and table MBEW)
    Thanks in advance.

    Hi Karthikeyan,
    Tcode MR51 check your all material document currency key for amounts in the system which document change to price see you..
    MBEW is last average price listed.
    You need to change average price use to Tcode MR21
    Regards,
    Cem ATES

  • Problem with moving average

    I have to create a report which displays rolling average of revenue.
    The report contains two columns week and avg revenue. I have to display only ten weeks from the current week.
    For each week the revenue should be calculated as follows;
    weeks     actual revenue     Avg revenue
    1     10          10     
    2     20          (10+20)/2
    3     30          (10+20+30)/3     
    4     40          (10+20+30+40)/4
    5     50          (20+30+40+50)/4
    6     60          (30+40+50+60)/4
    (current week-10 weeks)
    current week
    I have used Mavg(actual revenue, 4) to calculate avg revenue.
    I am getting the correct values. However if I apply a filter say weeks between current week and (current week-10 weeks), I am facing a problem.
    My (current week-10 weeks) is now showing avg revenue as 10 which is my actual revenue amount.
    But i would like to show the revnue amount as an avgerage of (current week-10 weeks) and previous three weeks.
    The filter to limit the number of weeks is applied before calculating the moving average. Is there anyway to calculate the moving average first and then apply the week filter to report.
    Pls help me solving this.
    Thanks

    Do this:
    Have the measure as :
    case when Periods."Weekdate" > TIMESTAMPADD(SQL_TSI_WEEK, -10 , CURRENT_DATE) then MAVG ("Sales Measures".Units, 4) else 999999999 end
    And then apply filter on the above measure column as :
    Case when Periods.Weekdate > TIMESTAM... ' is not equal to / is not in 999999999
    Let us know how it goes.
    PS : To prevent runaway query, you may want filter it further by Periods."Weekdate" > TIMESTAMPADD(SQL_TSI_WEEK, -15 , CURRENT_DATE)

  • Moving Average in a Report Section

    Hi there,
    I am displaying a measure in a chart that has three data points. The measure is 4 day moving average of a metric. Let's say my query brings back the last 6 days, which enables me to calculate the 4 day moving average for days 4, 5, and 6.
    I use the Previous() function to calculate the moving average:
    =(metric + Previous(metric) + Previous(Previous(metric)) + Previous(Previous(Previous(metric)))) / 4
    I don't want to show days 1, 2, and 3, so I filter these out of the chart and wrap a NoFilter() around the moving average. Everything is good so far.
    The problem arises when I section on a dimension. I can't seem to get the correct values unless I display all 6 data points in each section. NoFilter() doesn't seem to work.
    Has anyone run into this before? Does there exist a solution for this?
    Any help would be greatly appreciated.
    Thanks,
    Allan

    I figured it out:
    NoFilter([[4wkMvAvgMeasure]]) ForEach ([[day]]) In Section
    Thanks,
    Allan

  • How to get Moving Average Price ( MAP ) & Standered Price in BW

    Hi all,
    I want to get the Moving Average Price ( MAP) & Standered price in BW Report.So that please suggest me
    1. which Cube I have to use &
    2.  which datasource having that Moving Average Price ( VERPR) Field.
    If having other Procedure to calculate Moving Average Price in BW .
    please give me these details.
    Thanks,
    kiran

    Hi Kiran,
    0IC_C03 Cube can be used to bring the fields you require.
    Please search forum post by Anil Kumar, link is not available  thats why i am copying the text here.
    You need to enhance the Standard DS of Infoobject 0MAT_PLANT and Infoobject 0MAT_PLANT to include these 2 fields.
    And you need to enahance the 0IC_C03 cube to include 0MAT_PLANT and need to complete the mapping in all 3 Update rules for this added Infoobject.
    And you need to upload the attribute data of 0MAT_PLANT as full upload every day.
    In the reports , you need to dependent on Formula varibles with replacement path with standard price an MAP price attributes of 0MAT_PLANT. So if you go with these formula variables with replacement path, you should take 0MAT_PLANT characterstic into rows as a prerequiste.
    If you want to avoid this prerequisite, then take a look on How to calculate with attributes values.
    Other wise you need to do the calculations at 0MAT_PLANT level by a base query after every upload,and the result should be stored in TODS by APD .And then you can final report with out 0MAT_PLANT in rows upon this ODS.
    please see this links
    Re: 2lis_03_um and MBEW- STPRS
    Re: How to get Moving Average Prince and Standard Price in BW (inventory cube).
    Hope this Helps.
    Thanks
    CK

  • Moving Average price valuation

    Hi,
    We are maintaining rawmaterial at V-Moving Average price in the material master Record, so the consumption will be booked at V  price, but what about the closing valuation of rawmaterial, whether it is valued at V price or any other value.
    Second Query is how the price difference will be posted, how the system calculates the price difference whether at V price, whether it will post price difference or not.
    please provide the info i will assign points.
    sd/-
    Rajesh

    1. Both the consumption & the closing valuation of the raw-materials will be at "V" (moving average price).
    2. When the materials are mantained at "V" (moving average price), there is NO price difference varaince. All the price difference flows to the material valuation itself.
    Hope this helps you.

  • Moving Average Price for Sales stock and Project stock of a material

    Hiya Gurus,
                     I am developing a report to display inventory details. My requirement is that I have to display the Moving average price of a material for all Valuation type. I also need to display the Moving average price if a material has got Project stock or Sales stock.
                     In MBEW table I can get the Valuation type and its Moving average price, but how can I find the moving average price for the same material if it has got Sales stock and project stock. Please let me know the table and field where I could get the relevant data.
                    Kindly help me on this, it would be deeply appreciated.
    Cheers,
    ZIa

    Hi
    can you look at tables
    EBEW                             Sales Order Stock Valuation
    QBEW                             Project Stock Valuation
    Nat

  • Moving average Price for Material is Negative

    HI Friends,
    I am doing MIRO for PO where its giving me error while posting the Invoice that
    Moving average price for material is negative
    Can any please help me to resolve this.
    what would be the implications if the price difference is too high b/w MAP in Invoice .
    Thnaks
    Purna Nalluri

    It is ofcourse bcoz there is price difference in the between PO and IR....
    so as per the calculations the MAP becomes negative....
    The formula for it is :
    Difference/Current stock holding + current moving average...
    Pls check you price entered at PO and IR....
    There are no any implecations...excepts the price differece is reflected in the MAP of MMR....
    hope it helps...
    Regards
    Priyanka.P
    Edited by: Priyanka Paltanwale on Sep 23, 2008 7:28 AM

  • Error: moving average price negative while doing MIRO

    Hi Experts,
    I am doing MIRo for PO where its giving me error while posting the Invoice that:
    Moving average price for material is negative: XSEPSNPW045CX 1044
    The MAP maintained in material master is 39,979.71 and in the invoice and GRN is 69,049.58. 
    Can any please help me to resolve this.
    what would be the implications if the price difference is too high b/w MAP in Invoice amount.
    and
    what happen when we paintain the amount in mr21.
    Regards,
    Sonali.

    Hi,
    Pls check your price in MMR (MAP price) and then check the IR price of material ....
    Example:
    MMR MAP Price = 5.00 EUR
    If IR price = 30 .00 Eur
    IN YOUR CASE:
    The MAP maintained in material master is 39,979.71
    and in the invoice and GRN is 69,049.58.
    So MAP PRice defined in the MMR is lesser than the IR price...
    so the MAP will get negative...
    Hope it helps...
    Regards
    Priyanka.P
    AWARD IF HELPFULL
    Edited by: Priyanka Paltanwale on Sep 2, 2008 7:49 AM

  • Using Moving Average Materials with MF42N (Repetitive Production)

    Version: ECC 6.0
    I have a "Is this possible" question.  I know this isn't a best business practice, but thought I'd anyway.  Here goes ...
    A material that uses Moving Average (referenced as Material123 below) has the following two materials in its BOM:  (1) Moving Average (Material456), and (2) Non-valuated material, material type = LEER (Material789).
    The 1st material in the BOM (Material456) is Liquid Oxygen.  This product is purchased from a vendor and received into inventory via movement type 101.
    The 2nd material in the BOM is an empty cylinder (Material789)
    The parent material (Material123) being produced is gaseous Oxygen (Oxygen in gas form).
    Basic production process:  Liquid Oxygen is the raw material, it is pressurized and stored in a cylinder in gaseous form (for clarity, you've probably seen cylinders before, the two obvious examples of cylinders are propane cylinders used on barbeques and helium cylinders used to blow-up balloons).
    Assumptions:  (1) We do not want to do a cost roll, (2) We want to report production (TCode=MF42N) to consume the Bulk Oxygen (Material456) and the cylinder (Material789), and create the finished good (Material123), and (3) We do not want to burden the cost of the parent material (Material123) with direct costs, we only want the material costs.
    If you read through the assumptions you can see that this is not proper accounting for a production process (i.e. the direct costs in the production process are not capitalized -- labor, power, etc.), if you can get beyond that I was wondering if anyone has ever set anything like this up?  I tried to set this up and report production in my test environment, I got the materials created, the BOM created, but when I tried to report production it gave me an error, it needs a production version and/or a cost collector.
    If anyone has done anything like this I'd be interested in knowing if it is possible to report production with a setup like this.  Thanks.

    Using CO production orders may solve your problem. They dont need PP or product costing to be implemented. Costs can be flexibly posted and there are not many demanding requirements for this.
    Tcode:KKF1
    Link: [http://help.sap.com/saphelp_erp2004/helpdata/EN/82/e72326b11411d29f60080009b0db33/frameset.htm]
    Thanks
    Naveen

  • Updation of Moving Average Price

    Dear Experts,
    My MM period is open for 2 months (i.e for July and August Now) . One of our raw material is Limestone.
    From July 1st there were several Receipts and Issues of limestone in SAP.
    In August 9th our survey team found that in our stock we have 25000 TON limestone excess. (Due to Callibiration error)
    i.e If the current stock in system was 10000  TON the real Physical stock in storage was 10000 + 25000 TON.
    We have created a Free of Cost PO for 25000 TON to account the excess quantity of Limestone in Stock.
    MIGO Goods Receipt for the Free of Cost PO was done on 31.07.2011.
    Because of the extra 25000 TON Free of Cost Limestone Receipt the Moving Average Price of the Material got Updated. (But only from 09-August-2011 not from 31-July-2011)
    I want system to calculate the new moving average price and update all the documents posted from 31-July-2011. MY MM period is not closed.
    Is it possible to do so and how. Please Help.
    Thanks

    Hi
    The physical inventory is carried out on the basis of stock management units.A stock management unit is a non-divisible part of a stock of materials for which a seperate book inventory exists.A stock management unit is uniquely defined by
    Material
    Plant,storage location
    Stock type
    Batch
    Special Stock
    Each stock management unit of a material is counted seperately,and the inventory diffreneces are posted per stock management unit.
    The physical inventory process comprises three phases
    1)Creation of physical inventory documents(MI01)
    2)Entry of Count(MI04)
    3)Posting the difference(MI07)
    1)In the first phase ,you create the physical inventory documents.SAP systems provide several procedures for mass-generation of PI documents.After selecting the stocks to be counted and creating the PI documents,you print out the documents in order to start the counting process.A physical inventory document cotains data that include
    >The plant and storage location in which the count has to take place
    >The date on which the count has to take place
    >The materials to be counted
    >the stock types to be counted
    >The status of the item
    >The status of the PI document
    When creating a PI document,you can specify a physical inventory nuber in the document header.This physical inventory number facilitates selection of the PI documents to be processed during entry of the count data,posting the diffrences, and in evaluations.
    2)Entering the physical inventory count:For the physical inventory count,you must print out the PI document and forward it to persons responsible for the count.You can enter the stock figures in the system with and without reference to a PI document.When entering the physical inventory count,you can enter a percentage variance of the count quantity from the book inventory,above which the system issues a warning message.
    3)You can post the inventory diffrences either via list of differences or via seperate transactions.When an inventory difference is posted,the system creates a material document and corrects the stock figures,and an accounting document recording the necessary accounting movements.
    Hope this will be helpful for you.
    Regards,
    Sandesh Sawant

  • Moving average price not updatet when sales order stock

    Sales order stock is ioncluded in calculating moving average (at goods receipt there is no new valuation type created)
    It is okay with replenishment orders (regular stock)
    I first thought it had to do with Spec. Stk Valuation indictator (but this one is set to 'M', which seems right for me.
    Does anyone have a clue what I can do so my moving average value is also calculated based on sales order stock and not only regular stock?
    Kind Regards
    Kevin
    Edited by: Kevin Gielen on May 5, 2010 2:44 PM

    Spl Stock Valution must be - A (not M) to valuate along with normal stock .
    Ensure following configuration is there
    1. create Requirement class in OVZG . Maintain required account assignment category under account assginment subscreen
    2. Create requirement type in OVZH . assign this req.class to req.type
    3.Assign requirement type to sales item categories for which you need this VSO functionality
    4.Goto SM30 and give table V_T459K_K ,mainatain ,for your requirement class under valuation field maintain M or A(put F1 for moreinfo)
    5.Take SD consultant help to setup schedule line category(SC) for this item category ,it should have account assignemtnt category and PR order type - VOV6 and assign this SC to item category in VOV5
    6. Now create SO which will populate the above created item category (if not check with SD consul to populate the above item category)
    7.convert the PR generated through above SO into PO
    8.In PO under account assignment tab you could see BSX account and it must be greyout .
    9.Do GR ,stock will be updated in MBBS report.
    it resolves your requirements
    check point in each transaction:
    after SO ,check VBAP- KZBWS = M or A (which you have maintained in requirement class)
    PR from SO, EBAN-KZBWS =M or A and PO also will have EKPO-KZBWS = M or A

  • Moving Average Price for Non-Valuated Material

    Hello Experts
    The question may seem to be quirky but need your advice for the below.
    My client is buying non-valuated material against a cost center, they do not want to keep the stocks valuated. No value update only quantity update. The accounting documents are the following when the GR is done by receiving folks
    Qty of material XYZ goods receipted = 10
    Debit     Consumption GL   12345678       10 USD          Cost Center ABC123 (This is a warehouse cost center)
    Credit    GR/IR account                            10 USD
    Qty of mateiral XYZ issued = 5
    The goods are later on issued to Production cost center and the client was the below entries to be passed with MOVING AVERAGE PRICE.
    Debit    Consumption GL 12345678           6 USD          Cost Center ABC456 (This is production Cost center)
    Credit   Consumption GL 12345678           6 USD          Cost Center ABC123 (This is warehouse cost center)
    I am aware that as this is a non valuated material the above entry is not possible. Maybe, I will use BAPI_ACC_DOCUMENT_POST for the generating the accounting document when the goods are issued from warehosue to production center.
    My question is how can i get the moving average price.
    Regards
    Chokkalingam Pillai

    you can have an accounting view for non-valuated materials, this helps for example with purchase requisitions as they could take the valuation price from the material master and the user does not need to enter a valuation manually.
    But the material master moving average  price cannot be calculated and updated automatically, as it is not foreseen in any standard program to do this for cost center procurement, since SAP only calculates a MAP for valuated stocks.
    Further it is not logical to issue non-valuated stock valuated (even with a different price) from cost center to cost center.
    It looks like you want to  have a kind of internal billing for warehouse services, as you end up with a negative amount in the warehouse cost center which is then the profit.
    Why don't you just  create a report to run at the end of the month, listing all goods issue movements with their cost centers and taking the price from last PO (or from material master if you decide to maintain it manually) and use this for a manual cost center posting in CO module

  • Moving Average Price---Intercompany sales process

    Hi,
    I have a special requirement in Intercompany process..
    I want the Ordering company to be charged  with Moving Average Price of the Material instead of the Normal Price.
    Can some on help me out with this?
    Thanks,
    Challa.

    Hi,
    In general i hope, system will not copy the moving average price from the material master through VPRS Condition.  In case its not copied then you need to write the logic in alternative condition coloum to copy the moving averate price.
    Please confirm whether VPRS is working for moving average price, if not then develop the logic as below -
    based on Material and plant, go to table MBEW with selection as MATNR and WERKS bring the value from the field VERPR where VPRSV=V.
    Plese confirm for my knowledge also
    Regards
    Goutham

Maybe you are looking for