Creating function to calculate average value

Hi,
The below query was successfully return an average value. It returned 1 row.
SELECT AVG(Volume)
FROM security
WHERE
Type = 'Future' AND
Rating = 'AAA' AND
Code = 1 AND
(Day = ''14-mar-09' OR
Day = '16-mar-09' OR
Day = '');
I tried to use that function on my created function below.
CREATE OR REPLACE FUNCTION fn_Vol_Average
( v_DayLast_1_Week IN DATE,
v_DayLast_2_Week IN DATE,
v_DayLast_3_Week IN DATE )
RETURN NUMBER IS
v_Vol_Average NUMBER;
BEGIN
SELECT AVG(Volume) INTO v_Vol_Average
FROM security
WHERE
Type = 'Future' AND
Rating = 'AAA' AND
Code = 1 AND
(Day = v_DayLast_1_Week OR
Day = v_DayLast_2_Week OR
Day = v_DayLast_3_Week);
RETURN NVL(v_Vol_Average, NULL);
END;
I called that function by the following query. it was work, however it return the whole rows. It looks like the function perform the average calculation of each rows on the table.
Can anyone help me what is going on with the logic?
select fn_Vol_average('14-mar-09','16-mar-09','')
from security
--

But since your function calculates the average over the whole security table, you wouldn't call this from a select statement which also reads the security table.
You just want to execute it once.
declare
   l_vol_average number;
begin
   l_vol_average := fn_Vol_average('14-mar-09','16-mar-09','');
   dbms_output.put_line(l_vol_average);
end;By the way, be careful with your date parameters. You should use TO_DATE with a proper format mask to prevent conversion errors.

Similar Messages

  • Use Planning Function to calculate new value

    Hi All,
    I have what seems to be a simple problem, but no success in resolving.
    I have 3 planning keyfigures:
    -Units
    -Price
    -Value
    The price field is populated from another planning sheet.
    The unit field is entered by the user.
    The value should be calculated by planning function when button pushed.
    I have tried just basic "Value=Units*Price", but always comes back zero.
    I have also tried more complex "{Value, CharA, CharB, CharC} = {Units, CharA, CharB...." for each characteristic.  Still zero.
    It must be multipling by zero, but not sure how to avoid.
    If I put "Value=Price", it works. If I put "Value=Units", it works. If I put "Value=Units+Price", it works.
    Please help.
    Terrence

A: Use Planning Function to calculate new value

Here is the details.
In the infoprovider the data is like this:
Country/    Product/     Unit Sales/     Price/      Value
DE/             Shirt/            50/                 0/             0
DE/             Shirt/              0/             100.00/        0
The query is display:
Country/    Product/     Unit Sales/     Price/      Value
DE/             Shirt/            50/              100.00/         0
I have tried the following 2 formulas:
Formula 1:
= {Unit Sales} *
Formula 2:
FOREACH Country, Product.
{Value, Country, Product} = {Unit Sales, Country, Product} * {Price, Country, Product}
ENDFOR.
Both return zero for values.
Thanks,
Terrence

Here is the details.
In the infoprovider the data is like this:
Country/    Product/     Unit Sales/     Price/      Value
DE/             Shirt/            50/                 0/             0
DE/             Shirt/              0/             100.00/        0
The query is display:
Country/    Product/     Unit Sales/     Price/      Value
DE/             Shirt/            50/              100.00/         0
I have tried the following 2 formulas:
Formula 1:
= {Unit Sales} *
Formula 2:
FOREACH Country, Product.
{Value, Country, Product} = {Unit Sales, Country, Product} * {Price, Country, Product}
ENDFOR.
Both return zero for values.
Thanks,
Terrence

  • Calculate Average value based on Day ??

    Hello,
    I am trying to calculate the Average value based on a day. The data is presented as follows...
    Day          SOCount
    Mon                34
    Mon                 56
    Mon                 67
    Tues               24
    Tues               25
    Tues               23
    Weds              45
    Weds              69
    The issue im having is that the Day column needs to be grouped first and the SOCount sumed together. Then the Average SO Count needs to be calculate based on this.
    Thanks

    Thanks for the reply,
    The solution you have provided only gives me the average of the count of the SO Count, not the actual average of all the values added together then  divided by the count..
    The report i am creating only has charts in it. So i am trying to create a chart showing the
    Average Sale Order Value by day.
    I should have metioned this from the start, sorry.
    Is it possible to do ?
    Edited by: davitali on Nov 4, 2011 6:32 AM

  • Script logic to calculate average value on nodes - SAP BPC NW 10.0

    Hi experts,
    I need to have in the parent members of the dimension TIME (2014.Q1, 2014.Q2,  2014.Q3, 2014.Q4, 2014.TOTAL) the average value of  their children and not the sum. For example :
    2014.01        2014.02         2014.03        2014.Q1
        1                  2                    3                  2                                          
    2 = AVG(1, 2, 3)
    I tried the script bellow but it doesn't work , it throws the error " ReferenceError : AVG is not defined"
    *SELECT(%TIMESET%,"[ID]",TIME,"[CALC]='Y'")
    *XDIM_MEMBERSET TIME = %TIMESET%
    *XDIM_MEMBERSET MEASURES = PERIODIC
    *WHEN DIM1
    *IS C02
    *WHEN TIME
    *IS %TIMESET%
    *REC(EXPRESSION = AVG(Descendants([%TIMESET%].CURRENTMEMBER)), TIME = %TIMESET%)
    *ENDWHEN
    *ENDWHEN
    *COMMIT
    How can I achieve this ?
    Thanks
    Maha

    The best way is to enter 2 accounts: Productivity and Area, calculating by dimension member formula:
    ProductivityPerHectare=IIF([Area]=0,NULL,[Productivity]/[Area])
    If you have to enter ProductivityPerHectare and Area, then in script you can calculate Productivity:
    *WHEN ACCOUNT
    *IS Area
    *REC(EXPRESSION=%VALUE%*[ACCOUNT].[ProductivityPerHectare],ACCOUNT=Productivity)
    *ENDWHEN
    *WHEN ACCOUNT
    *IS ProductivityPerHectare  //user input
    *REC(EXPRESSION=%VALUE%*[ACCOUNT].[Area],ACCOUNT=Productivity)
    *ENDWHEN
    Then dimension member formula:
    ProductivityPerHectareCalc=IIF([Area]=0,NULL,[Productivity]/[Area])
    You can use arithmetic average of ProductivityPerHectare only if Area is always constant.
    In this case you can create some dummy account member DUMMY and fill it with 1:
    *WHEN ACCOUNT
    *IS ProductivityPerHectare  //user input
    *REC(EXPRESSION=1,ACCOUNT=DUMMY)
    *ENDWHEN
    Then dimension member formula:
    ProductivityPerHectareCalc=IIF([DUMMY]=0,NULL,[ProductivityPerHectare]/[DUMMY])
    Vadim

  • How to calculate average value?

    Hi all,
    I'm using Lumira 1.15. I'm doing some practices with the sample dataset BestRunCorp... I want to calculate the average value of gross margin which is grouped by lines so that I can use a line chart to show the difference between the gross margin value and average value.
    How can I achieve this ?
    Best regards,
    Shuang

    It looks like it calculates the average based on the dimension
    See below:
    If you take the "Best run" Excel file, sort by country, calculate the average in Excel, it matches Lumira's 4,056 (for Argentina)
    I am not sure I follow your divide by 12 logic?

  • Read-in CSV and Calculate Average Value

    I've got a csv file which I'm reading in but need to calculate the average value of the second column (CPU). It's in the following format:
    Date CPU
    01/09/2014 25.3
    02/09/2014 22.3
    03/09/2014 26.2
    04/09/2014 22.1
    I basically need the average CPU for the month. Any advice?
    Thanks in advance
    Adam

    "Date","CPU"
    "01/09/2014","25.3"
    "02/09/2014","22.3"
    "03/09/2014","26.2"
    "04/09/2014","22.1"
    '@ | sc test.csv
    (Import-Csv test.csv | measure CPU -Average).Average
    23.975
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • How to calculate Average value stock value - MC.B

    Hi All,
    When we execute T code MC.B  we get material analysis report . In it we have a column AVG VAL STOCK VALUE.
    Can some one explain how it is calculated. I see the formula
    The average stock value of the valuated stock is calculated using the formula:
             beginning stock value + n stock value at month´s end
                                    n + 1
    Can Some one explain how it is calculated and what 'N' stands for?
    Thanks,
    Vengal Rao.

    MC.B is inventory turnover.
    In the selection screen you enter how many periods to analyze.
    by default it is today 06/11 to 08/11
    n is the number of periods
    so you have a beginning stock of period 06/11
    + end stock of period 06/11
    + end stock of period 07/11
    + end stock of period 08/11 (which is todays stock)
    so the formula is:
    beginning stock value + 3 stock value at month´s end
    3 + 1

  • Average value of N samples

    Hi,
    I have a problem. I'm reading data continuously from analog input. I want calculate average value when I press button START. Average value should be calculated from samples which are defined by 'Number of samples' and 'millisecond multiple'. When all samples are read, average vale should show.
    The problem is that when number of samples is higher then 10, it doesn't work.
    Can someone tell me what I did wrong?
    Thanks
    P.S.. I saw that there was something like this but I can't open it because I use Labview 8.5
    Attachments:
    Average.vi ‏35 KB

    For that you need to store the previous value for averaging... i have attached a VI regarding that ( sorry no time to cleanup ).. You can use the logic to calculate the average of the samples (Still am not clear about you requirement).
    The best solution is the one you find it by yourself
    Attachments:
    Average_anand.vi ‏26 KB

  • How to calculate average if some of measure values are 0

    Hi
    I created a webI report on top of a Bex query, I have a more than 10 different measure in WebI report column on which i need to calculate average.
    If I  use the Average function provided with in WebI report it is calculating average for the measures which are having 0  values too, but i need to calculate average on a column only for those values which are not 0
    Ex:  Measure Quantity has values in the report like
    100
    100
    0
    100
    100
    Average function is calculating as 400/5
    but I need 400/4, because one of the value is 0, so i need to avoid that count which is zero and should divide it by 4 but not 5.
    One way is to custom create measure for all measures and make a if else condition and divided by that custom measure, but is there any other procedure?

    i hope this can help
    =Average([myMeasure]) Where ([myMesyre] <> 0)
    good luck
    Amr
    before the 0 add <> not Equal too sign < and >
    Edited by: Amr Salem on Jan 19, 2011 9:29 AM
    Edited by: Amr Salem on Jan 19, 2011 9:30 AM

  • Calculate the average value

    the data I measured changed rapidly, so i want get the average value of the data
    Do not tell me to use mean.vi , i have already know that.
    and i got an idea which is add the data into an array every time, then sum of all the data value and take the result divide by the number of elements
    but i dont know how to achieve that, anyone can build a simple vi to show me ? thank you
    i have attached my vi which is using mean.vi to calc the average value, you can delete it and using in your way ,  thank you !
    Solved!
    Go to Solution.
    Attachments:
    EN-new.vi ‏274 KB

    Hi I got a similar issue for averaging. I used the mean.vi from the math function but the average is rolling when i run it. I am trying to calculate the average for the data i read to the RT FIFO (which is around 40000 lines).I got the writing part working, however, when i am reading the data, I couldn't get it working. I thought i read the data as a 1-D array, and then pass it to the Mean.vi and then got the result. But seems like the mean is only showing the last data in the array.
    Can someone help me with this??
    Attachments:
    FPGA-vi.png ‏242 KB
    RT-vi.png ‏182 KB
    RT-2mod.vi ‏515 KB

  • How to create a procedure function with a return value of ref cursor?

    Can anybody provide a sample about how to create a procedure function with a return value of REF CURSOR?
    I heard if I can create a function to return a ref cursor, I can use VB to read its recordset.
    Thanks a lot.

    http://osi.oracle.com/~tkyte/ResultSets/index.html

  • Calculate single value as ranked number function does not apply in CR

    Hi everybody,
    I built up a query with the SAP BEx Query designer. For one key figure I enabled the function "Calculate single values" as ranked list. So the query has the following result.
    Instead of...
    Score
    1220
    2032
    2390
    2389
    ...I got...
    Score
    1
    2
    4
    3
    Unfortunately when importing the query to Crystal Reports Crystal is just importing the key figure itself - the ranked list does not exist... so the output is the same as in the first example.
    I tried to rebuild the formula with crystal means using the Rank function but I failed...
    Can anybody provide a workaround for me?
    Is there another way as using the formula workbench?
    Best regards,
    Sebastian

    Hi Ingo and everybody,
    I used now the following function using the Nth largest function:
    If nthlargest(1, {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]})
       = {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]} then "1"
    else if nthlargest(2, {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]})
       = {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]} then "2"
    else if nthlargest(3, {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]})
       = {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]} then "3"
    else if nthlargest(4, {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]})
       = {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]} then "4"
    else if nthlargest(20, {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]})
       = {TECHNAME_OF_QUERY.[Measures]-[9XU9YT56S6PRL7DR80I3DK9RA]} then "20"
    The formula is not very handsome and will fail, if the number of records exceeds...
    Are there any alternatives?
    And: Is there a possibility to change the field name, because those clumsy field names cause that the whole formula is almost unreadable. Or is the only way to build subreports?
    Regards,
    Sebastian

  • Creating a function and passing query value

    I have what I thought was a pretty easy to resolve situation:
    I want to concatenate two query fields, if the 2nd one isn't empty.
    I created a function:
    <cfargument name="q1" value='#query.q1#' />
    <cfargument name="q1a" value='#query.q1a#' />
    <CFSET variables.myPunct = ": ">
    <cfset variables.ResultVar="">
    <cfif Trim(arguments.q1) NEQ "">
    <cfset variables.ResultVar='#arguments.q1#'>
    </cfif>
    <cfif Trim(arguments.q1a) NEQ "">
    <cfif variables.ResultVar NEQ "">
    <cfset variables.ResultVar='#variables.ResultVar &
    variables.myPunct#'>
    </cfif>
    <cfset variables.ResultVar='#variables.ResultVar &
    arguments.q1a#'>
    </cfif>
    <cfreturn variables.ResultVar>
    This is basically just the example they provide in the online
    instruction, with the names changed.
    In the detail band of my report, I have an expression builder
    field containing: report.mytestfunction()
    When I run this, I get: Element Q1 is undefined in ARGUMENTS.
    I've tried this ninety different ways (literally). It seems
    very clear to me that the query.q1 (for that matter, any of the
    query results) are NOT getting passed to the function. I have tried
    making the expression: report.mytestfunction(query.q1). I have
    tried creating an input parameter.
    The documentation on this is ridiculously limited,
    considering that the ability to implement conditional logic depends
    entirely on the "function", as far as I can tell. I can in no way
    get the function to interface with the query results. If is set
    fixed values in the function, as opposed to trying to use the query
    variables, it outputs fine.
    Any ideas?

    That has got to be the only way I DIDN'T try, although I
    could swear I tried that, too. Maybe I didn't have the "required"?
    I don't know. I know it works now. For the record, FUNCTION:
    <cfargument name="q1" required="yes" />
    <cfargument name="q1a" required="yes" />
    <CFSET variables.myPunct = ": ">
    <cfset variables.ResultVar="">
    <cfif Trim(arguments.q1) NEQ "">
    <cfset variables.ResultVar='#arguments.q1#'>
    </cfif>
    <cfif Trim(arguments.q1a) NEQ "">
    <cfif variables.ResultVar NEQ "">
    <cfset variables.ResultVar='#variables.ResultVar &
    variables.myPunct#'>
    </cfif>
    <cfset variables.ResultVar='#variables.ResultVar &
    arguments.q1a#'>
    </cfif>
    <cfreturn variables.ResultVar>
    In the "Detail" band, called function:
    report.mytestfunction(query.q1, query.q1a)
    Thanks for the tip. I'm going to go take a long walk on a
    short pier now.
    max

  • How to calculate Average of Keyfigure

    Hi Gurus,
    I have a requirement where I have to calculate average of key figure value for 1 material.
    I tried using 'Average' in exception Aggregation but it just sums up everything.
    Can anyone please explain?
    Thanks

    Hi
    1. Include the key figure you want to average into the columns; call it KF1
    2. Create a Formula; call it CTR1, and in the detail view put a 1. (This 1-value is not used except to avoid an error in the formula syntax checker.) On the Aggregation tab, choose Exception Aggregation: Counter for all Detailed Values, and for the Ref. Characteristic, choose the same characteristic as the lowest level characteristic in the initial view of the output. E.g. if you only have 0CALMONTH in the output, choose 0CALMONTH. When you run this, the total at the bottom of this column should be equal to the number of rows in that column. Note that we use Exception Aggregation here so that the total at the bottom is calculated before the output is generated and is available to other formulas in the query design; if we were to use the Calculation tab it would look the same to us in that the total would appear at the bottom, but the calculation would occur too late for us to use within the query.
    3. Create a second formula, call it AVG1. The formula will be:
    SUMGT KF1 / SUMGT CTR1
    SUMGT accesses the Overall Result value at the bottom of the KF1 and CTR1 columns. You can find the SUMGT function in the Data Functions folder - turn on technical names first; the description is Overall Result. You could instead use SUMRT; the difference is that SUMGT will use the filters applied in the filter block; SUMRT will ignore them.
    3. Run the query. You should see the Average in every cell in the Average column. You can use this formula as input to another formula, or just use ( SUMGT KF1 / SUMGT CTR1 ) within a formula to access the average value.
    Thanks

  • Average Value

    Dear all,
    i have to calculate a query which contains the following data
                   ¦ Day 1 ¦ Day 2 ¦ ... ¦ Day 7 ¦ Avg. week ¦ Avg. month ¦ Avg. year ¦
    Value 1
    Value 2
    In Colum 1 to 7 the daily revenue should be displayed; in the column Avg. week i should show the daily average (sum of clumn 1 to 7 / 7). that's easy. but how should i calculate the monthly average or the yearly average ?
    i don't want to create 365 columns in the query to calculate just a average for the year? I tried with key figures with exeptionel aggregation (AVG) but that does not help. If i have daily data loads i have the same values in this key figure as in the others (of course).
    Any idea ?
    If preferred I could provide an Excel-File. Perhaps it is then easier to understand.
    Thanks,
    Marc

    Hi Marc,
    Create a structure:
    in first object  restrict revenue by calday and offset calday
    (a user entry variable)  by 6 ( ex if calday is 08/11/07 u will get revenue for  08/05/07)
    similarly do it 6 more time with offsets descending untill 1  and in the last object no offset which will give you the present day( as entered in the variable 0calday)
    now create a formula object  avg week ( sum of all above columns /7)
    now create another object for month(you can hide this if you want by hding it funder properties) : here restrict revenue by variable 0calmonth
    now create a formula object and use the above field value and calculate average using the available mathematical functions
    similarly do it for a year also (0fiscyear)
    Hope this helps
    Anand Raj

  • Maybe you are looking for