To find average

hi,
columns
year_month_no
200901,200902 etc
quantity,
10,30,50 etc
part
AB,BC,ZD etc
Average for last 12 months excluding current month
for finding average for previous 12 months of quantity iam using
AVG(quantity) OVER (ORDER BY year_month_no
ROWS BETWEEN 12 PRECEDING AND 1 PRECEDING) AVG_QTY_SALES
but year_month_no is repeating in the table
like
200901 10 AB
200901 20 BC etc
so when i am using rows between 12 preceding 1 it is fetching data for the same year_month_no because it is repeating instead of rolling up to previous 12 months..is there any solution for this..please help me as i am a naive user to oracle
thanks in advance
aswin

Hi, Aswin,
It sounds like you need a PARTITION BY clause:
AVG (quantity) OVER (
               PARTITION BY  part     -- *****  ADD THIS  *****
               ORDER BY      year_month_no
               ROWS BETWEEN  12 PRECEDING
                    AND       1 PRECEDING
              ) AS ave_qty_sales"PARTITION BY part" menas that the function will be computed separately for each part. For example, owhen calculating the average for a row where part='AB', only the 12 preceding rows that also have part='AB' will be considered.
Is year_month_no a NUMBER? That's a bad idea. Columns that represent points in time should be DATEs.
You're using ROWS BETWEEN. so if there are two (or more) rows with the same part and year_month_no, then the preceding 12 ROWS might represent less that 12 months. On the other hand, if there are no rows for a given part in some months, the the ROWS could be more that 12 months. You might want RANGE BETWEEN instead of ROWS BETWEEN.
Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements) for all the tables involved, so the people who want to help you can re-create the problem and test their ideas. Also post the results you want from that data, and an explanation of how you get those results from that data.
In the case of a DML operation (such as INSERT) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
Explain, using specific examples, how you get those results from that data.
lways say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ {message:id=9360002}

Similar Messages

  • How to find Average & Max of a Restricted key figure

    Hi Friends,
    I have a restriced Key figure. How to find Average & Max for that Restriceted Key figure.
    Post Asap.
    Thanks = Points.

    Hi Friends,
    Let me explain my scenerio clearly.
    I need to have five columns as below with char Current Assigne.
                               No of open cases     No of Closed cases   Avg age of closed cases         Avg age of open cases          Max age of Closed cases
    Current Assigne.
    Thanks,
    James

  • How to find Average transaction size and average number of transactions/sec

    Would like to know
    1. how to find average transaction size
    2. number of transactions per sec
    using SQL queries. We also have statspack installed.
    Regards,
    Anirban

    SQL> select maxval,minval,average from SYS.V_$SYSMETRIC_SUMMARY where metric_name in ('User Transaction Per Sec');
    MAXVAL MINVAL AVERAGE
    .7 0 .149170735
    SYS.V_$SYSMETRIC_SUMMARY have to many other metrics check the one you need. (10G and above)
    Coskan Gundogar
    http://coskan.wordpress.com
    Edited by: coskan on Mar 31, 2009 12:42 PM

  • How to Format DataGridView Cells after user input, also find average of Timespans

    I'm a rather new to programming and slowly learning as best I can, and feel that I'm probably just getting hung up on some things because of my lack of overall understanding.  I've searched plenty online and these forums to figure out my issues, but
    somethings just go over my head or I can't figure out how to make it work for what I'm trying to do.
    On to what I'm trying to do.
    I'm working on building an app for scoring swim meets for our conference.  I'm using a lcal SQL DB for all of the data and have a DGV on my form.  We don't have timing systems so we take 2 times from stop watches and then need to do an average
    of the times to determine a swimmers time.  I have 3 fields for times, Time1, Time2 and AvgTime.
    What I'm needing help with is how do I allow the user to not worry about formatting the time they enter but have it automatically format what they input after they exit the cell on Time1 and Time2.  Then I need to have it figure out the average of those
    two times in AvgTime cell.  I'm able to get the averaging to work if I have the datatype set to decimal or int, but I can't get it to work if I have them set has TimeSpan.
    Below is the code I have currently.  As you can see I've got things commented out that I found online but couldn't make work.
    Thanks for taking the time to review this and help me out.
    Public Class EventScoring
    Private Sub EventScoring_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'MeetDataSet.DualLineup' table. You can move, or remove it, as needed.
    Me.DualLineupTableAdapter.Fill(Me.MeetDataSet.DualLineup)
    'TODO: This line of code loads data into the 'MeetDataSet.EventList' table. You can move, or remove it, as needed.
    Me.EventListTableAdapter.Fill(Me.MeetDataSet.EventList)
    'DualLineupDataGridView.Columns(5).DefaultCellStyle.Format = ("mm\:ss\.ff")
    MeetDataSet.DualLineup.Columns("AvgTime").Expression = "(([Time1] + [Time2]) /2)"
    End Sub
    Private Sub Sub_Btn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Sub_Btn.Click
    Try
    Me.Validate()
    Me.DualLineupBindingSource.EndEdit()
    Me.DualLineupTableAdapter.Update(Me.MeetDataSet.DualLineup)
    MsgBox("Update successful")
    Catch ex As Exception
    MsgBox("Update failed")
    End Try
    End Sub
    'Private Sub DualLineupDataGridView_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DualLineupDataGridView.CellFormatting
    ' If ((e.ColumnIndex = 5) AndAlso (Not IsDBNull(e.Value))) Then
    ' Dim tp As TimeSpan = CType(e.Value, TimeSpan)
    ' Dim dt As DateTime = New DateTime(tp.Ticks)
    ' e.Value = dt.ToString("mm\:ss\.ff")
    ' End If
    'End Sub
    'Private Sub DualLineupDataGridView_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DualLineupDataGridView.CurrentCellDirtyStateChanged
    ' If ((e.ColumnIndex = 5) AndAlso (Not IsDBNull(e.Value))) Then
    ' Dim tp As TimeSpan = CType(e.Value, TimeSpan)
    ' Dim dt As DateTime = New DateTime(tp.Ticks)
    ' e.Value = dt.ToString("mm\:ss\.ff")
    ' End If
    'End Sub
    End Class

    AB,
    If you're ok with your database other than working out this issue with time, you might want to give the following a try. It's pretty flexible in that you can give it a string or a decimal, and I'll explain:
    The string can be in the format of "mm:ss" (minutes and seconds) or in the format of "mm:ss:f~".
    The reason that I put the tilda there is because you're not limited on the number of decimal places - it will work out the math to figure out what you meant.
    Also though, you can give it a decimal value representing the total number of seconds. Do be sure to clearly denote that it's a decimal type (otherwise it will assume it's a double and will fail). Here's the class:
    Public Class SwimmerTime
    Private _totalSeconds As Decimal
    Public Sub New(ByVal value As Object)
    Try
    Dim tSeconds As Decimal = 0
    If TypeOf value Is String Then
    Dim s As String = CType(value, String)
    If Not s.Contains(":"c) Then
    Throw New ArgumentException("The string is malformed and cannot be used.")
    Else
    Dim elements() As String = s.Split(":"c)
    For Each element As String In elements
    If Not Integer.TryParse(element, New Integer) Then
    Throw New ArgumentException("The string is malformed and cannot be used.")
    End If
    Next
    If elements.Length = 2 Then
    tSeconds = (60 * CInt(elements(0)) + CInt(elements(1)))
    ElseIf elements.Length = 3 Then
    tSeconds = (60 * CInt(elements(0)) + CInt(elements(1)))
    Dim divideByString As String = "1"
    For Each c As Char In elements(2)
    divideByString &= "0"
    Next
    tSeconds += CDec(elements(2)) / CInt(divideByString)
    Else
    Throw New ArgumentException("The string is malformed and cannot be used.")
    End If
    End If
    ElseIf TypeOf value Is Decimal Then
    Dim d As Decimal = DirectCast(value, Decimal)
    tSeconds = d
    Else
    Throw New ArgumentException("The type was not recognizable and cannot be used.")
    End If
    If tSeconds = 0 Then
    Throw New ArgumentOutOfRangeException("Total Seconds", "Must be greater than zero.")
    Else
    _totalSeconds = tSeconds
    End If
    Catch ex As Exception
    Throw
    End Try
    End Sub
    Public Shared Function GetAverage(ByVal value1 As Object, _
    ByVal value2 As Object) As SwimmerTime
    Dim retVal As SwimmerTime = Nothing
    Try
    Dim st1 As SwimmerTime = New SwimmerTime(value1)
    Dim st2 As SwimmerTime = New SwimmerTime(value2)
    If st1 IsNot Nothing AndAlso st2 IsNot Nothing Then
    Dim tempList As New List(Of Decimal)
    With tempList
    .Add(st1.TotalSeconds)
    .Add(st2.TotalSeconds)
    End With
    Dim averageSeconds As Decimal = tempList.Average
    retVal = New SwimmerTime(averageSeconds)
    End If
    Catch ex As Exception
    Throw
    End Try
    Return retVal
    End Function
    Public ReadOnly Property FormattedString As String
    Get
    Dim ts As TimeSpan = TimeSpan.FromSeconds(_totalSeconds)
    Return String.Format("{0:00}:{1:00}:{2:000}", _
    ts.Minutes, _
    ts.Seconds, _
    ts.Milliseconds)
    End Get
    End Property
    Public ReadOnly Property TotalSeconds As Decimal
    Get
    Return _totalSeconds
    End Get
    End Property
    End Class
    I'll show how to use it by example:
    Option Strict On
    Option Explicit On
    Option Infer Off
    Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles MyBase.Load
    Try
    Dim averageSwimmerTime As SwimmerTime = _
    SwimmerTime.GetAverage("02:24:05", 145.3274D)
    MessageBox.Show(String.Format("Formatted String: {0}{1}Actual Value: {2}", _
    averageSwimmerTime.FormattedString, vbCrLf, _
    averageSwimmerTime.TotalSeconds), _
    "Average Swimmer Time")
    Stop
    Catch ex As Exception
    MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
    vbCrLf, ex.Message), "Program Error", _
    MessageBoxButtons.OK, MessageBoxIcon.Warning)
    End Try
    Stop
    End Sub
    End Class
    An advantage here is that since it returns an instance of the class, you have access to the formatted string, and the actual decimal value.
    I hope you find this helpful. :)
    Still lost in code, just at a little higher level.

  • Function to find Average salary

    Hello everyone,
    First of all I would like to say that I am a newbie to PL/SQL so please be patient with me. I am trying to create a function that will calculate the average salary for employees and compare the average salary to each employee's salary. If the employee's salary is lower than the average salary, my function will return true, elese it will return false.
    I think I have a great start but need some guidance on what to do next. Here's my function so far:
    CREATE OR REPLACE FUNCTION check_employee_salary
    (p_empno IN NUMBER)
    RETURN NUMBER
    IS
    lv_sal emp.sal%TYPE;
    BEGIN
    SELECT avg(sal)
    INTO lv_sal
    FROM emp
    WHERE empno = p_empno;
    RETURN (lv_sal);
    END;
    My function compiles but I can't figure out how to compare the avg(sal) to sal so that I can return true and false. Any guidance will be appreciated as I really want to understand PL/SQL and am trying very hard.
    Thanks

    Your function currently returns the average salary for a single employee, and since (in scott.emp at least) an employee only has one salary, it will return that.
    SQL> select empno, ename, job, sal, check_employee_salary(empno) from emp;
         EMPNO ENAME      JOB              SAL CHECK_EMPLOYEE_SALARY(EMPNO)
          7369 SMITH      CLERK            800                          800
          7499 ALLEN      SALESMAN        1600                         1600
          7521 WARD       SALESMAN        1250                         1250
          7566 JONES      MANAGER         2975                         2975
          7654 MARTIN     SALESMAN        1250                         1250
          7698 BLAKE      MANAGER         2850                         2850
          7782 CLARK      MANAGER         2450                         2450
          7788 SCOTT      ANALYST         3000                         3000
          7839 KING       PRESIDENT       5000                         5000
          7844 TURNER     SALESMAN        1500                         1500
          7876 ADAMS      CLERK           1100                         1100
          7900 JAMES      CLERK            950                          950
          7902 FORD       ANALYST         3000                         3000
          7934 MILLER     CLERK           1300                         1300
    14 rows selected.To report whether a specified employee's salary was above or below average, it would have to find the overall average (select avg(sal) from emp) and compare that to the specified employee's salary (select sal from emp where empno = p_empno). This would however be about the most inefficient way imaginable to derive this rather odd statistic. The easy way is using straight SQL:
    select empno, ename, job, sal
         , avg(sal) over() as company_avg_sal
         , case when sal < avg(sal) over() then 'Below'
                when sal = avg(sal) over() then 'Average'
                when sal > avg(sal) over() then 'Above'
           end as comparison
    from   emp;
         EMPNO ENAME      JOB              SAL COMPANY_AVG_SAL COMPARISON
          7369 SMITH      CLERK            800      2073.21429 Below
          7499 ALLEN      SALESMAN        1600      2073.21429 Below
          7521 WARD       SALESMAN        1250      2073.21429 Below
          7566 JONES      MANAGER         2975      2073.21429 Above
          7654 MARTIN     SALESMAN        1250      2073.21429 Below
          7698 BLAKE      MANAGER         2850      2073.21429 Above
          7782 CLARK      MANAGER         2450      2073.21429 Above
          7788 SCOTT      ANALYST         3000      2073.21429 Above
          7839 KING       PRESIDENT       5000      2073.21429 Above
          7844 TURNER     SALESMAN        1500      2073.21429 Below
          7876 ADAMS      CLERK           1100      2073.21429 Below
          7900 JAMES      CLERK            950      2073.21429 Below
          7902 FORD       ANALYST         3000      2073.21429 Above
          7934 MILLER     CLERK           1300      2073.21429 Below
    14 rows selected.

  • How to find average item price

    How can i find the average item price of an item throug quey or application

    Hi,
    Please review the following threads ..
    item_price
    item_price
    SQL query to display the price of an ITEM
    Re: SQL query to display the price of an ITEM
    You can also search for old threads which discuss the same topic --> [Average Item Price|http://forums.oracle.com/forums/search.jspa?threadID=&q=average+item+price&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001].
    Regards,
    Hussein

  • Find average at group level of multiple grouped fields

    Can this not be done in Crystal
    I am trying to total and average at the group level like this:
    ((Sum ({@Unscheduled}, {@monthName}))/(Sum ({@total}, {@monthName}))*100)
    --  {@Unscheduled} =           if ({Table_Name.status} = "Unscheduled" and not({Table_Name.StartDate}>= currentdate))
    then 1
    I am grouping by month. The formula {@Unscheduled} gave me the total for each month of that ticket type and I was able to sum 3 other ticket types and sum total of all ticket types. But when I try to find the average of each with this
    ((Sum ({@Unscheduled}, {@monthName}))/(Sum ({@total}, {@monthName}))*100)
    I get an error saying division canu2019t be done with zero, but there are no zeros  when shown separately on the report.
    I guess my question is Can you not perform calculations at the group level with multiple fields.
    Any insight would be appreciated and I apologize if this is somewhat incoherent.

    You could do this like this, I think:
    If Sum ({@total}, {@monthName}) = 0 Then
        0
    Else
        Sum ({@Unscheduled}, {@monthName}) / Sum ({@total}, {@monthName}) * 100;

  • Finding Average Timestamp

    Hey,
    I have a table with two columns: FILE_ID (NUMBER), ARRIVAL_TIME (TIMESTAMP).
    I want to figure out the average ARRIVAL_TIME for a given file. I can't seem to find out how to do this. When I try to execute the following:
    SELECT AVG(V.ARRIVAL_TIME)
    FROM FILE_ARRIVALS V WHERE FILE_ID = SOME_NUMBER
    I get this error:
    ORA-00932: inconsistent datatypes: expected NUMBER got TIMESTAMP
    I've found many examples of getting the average timespan between two timestamps or dates, but they don't fit my needs.
    Thanks!
    Jeffrey Kevin Pry
    Edited by: jeffrey.pry on Aug 19, 2010 5:44 AM

    Hey,
    I'm using 11g R2. I might be more clear if I say that I just want the average time the file arrives over a past period of days....
    ------- CREATE STATEMENT -------
    CREATE TABLE FILE_ARRIVALS
    FILE_ID NUMBER NOT NULL,
    ARRIVAL_TIME TIMESTAMP(6) NOT NULL
    ------- SAMPLE INSERTS -------
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/12/2009 13:45','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/13/2009 13:41','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/14/2009 13:46','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/15/2009 13:41','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/16/2009 13:40','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/17/2009 13:57','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/18/2009 13:12','MM/DD/YYYY HH24:MI'));
    INSERT INTO FILE_ARRIVALS (FILE_ID, ARRIVAL_TIME) VALUES (1,TO_TIMESTAMP('12/19/2009 13:53','MM/DD/YYYY HH24:MI'));
    So I want to figure out what time the file normally arrives.
    Thanks!
    Jeffrey Kevin Pry

  • Finding average value

    Hi,
    how to find the average  of  array like (1,2,3,4)using bls?
    Please give me the  solution for  this query.
    points will be rewarded.
    Thanks&Regards
    Gurunadh.

    Hi Gurunadh,
    you can use the Aggregate Statistics action block for this (under XML Functions in BLS editor) - it will give you average (mean) and a few other statistical values in one execution.
    However, this action only works on numbers which are in one column.
    This is also in the xMII help - http://help.sap.com/saphelp_xmii115/helpdata/en/Business_Logic_Services/aggregatestatistics.htm
    Sascha

  • Finding average amplitude of frequency

    Hey guys,
    I'm new to this forum and I am looking for some help with finding the average of a frequency-amplitude graph. I tried multiple example codes I've found on here and none of them really worked for me. I attached my program to this post. The problem I am having now is that my averaged graph looks exactly like my originial graph and I don't know why... theoretically I think I'm correct because I add one everytime the loop execute itself and then it divide the graph by the number I got and therefore it's the average. The average code is near the bottom of the picture I've attached, everything else works fine in my program. Please let me know what you think!
    Also, a lot of times I like to ask really obvious questions. Sorry if this is one of them! Thanks in advance for helping out and let me know if you need any addtional information!
    Attachments:
    HansLabView.JPG ‏151 KB

    I cannot tell how you have the express VIs configured from looking at an image.
    The averaging done by the spectrum express VIs keeps track internally of the number of iterations in much the same way as you are doing.  Open the VIs and look for yourself.
    So it appears that you have an averaged spectrum and an averaged spectrum divided by an integer.  It is not clear that you have an "instantaneous" on "un-averaged" spectrum.
    Lynn

  • Read, save and find average

    Hi all, 
    I am new to Labview and need some help please.
    I need to read data from frequency counter (e.g. 50.000123 MHz), save it and do a simple calculation (find an average).
    I only know how to read the data. I would like to display the every 5 or 10 values (in a block of array) save it and then take an average of them.
    Just to aknowledge the attached file is not my work but it works with my frequency counter and I found it on this forum.   
    Thanks     
    Attachments:
    fc_control_1.vi ‏56 KB

    I can open your VI, don't worry about that. Images do me no good.
    Well, do you know how a for loop works? And a shift register? (Actually, you can do this without a shift register because you are generating an array, but IMHO, it's a better solution.)
     Think of what you have to do in the programand write the steps down. Translating the steps into LabVIEW is your last step - It actually comes pretty naturally if you think about what you would have to do physically if you're the computer (since your steps chronologically are analogous to LabVIEW's dataflow), then you just have to figure out which output from one subVI or function goes to the input of the next subVI or function (i.e., syntax).
     BTW, the time function and "Time Delay" express VI are redundant. Take out the express VI.
    And, if you just want to write a column of data, isn't "write to spreadsheet file" doing that?
    Cameron
    To err is human, but to really foul it up requires a computer.
    The optimist believes we are in the best of all possible worlds - the pessimist fears this is true.
    Profanity is the one language all programmers know best.
    An expert is someone who has made all the possible mistakes.
    To learn something about LabVIEW at no extra cost, work the online LabVIEW tutorial(s):
    LabVIEW Unit 1 - Getting Started
    Learn to Use LabVIEW with MyDAQ

  • How to find average for non blank values

    I need to calculate avarage for each restricted key figures. There are some blank values in this restricted key figures. Now I need to sumup and divide by non blank count. Do you know how to do it? How to count non blnak values and find avereage.
    Thanks,
    Phani

    In the properties of Key figure used in column/row, Calculations section, you can maintain calculation type for result as well as single value. There is "Average of all values not equal 0" option is available.
    Rgds,
    Vikram.
    Edited by: Vikram Kate on May 22, 2008 11:23 AM

  • Find average of 3 boxes to the nearest 0.50 inch.

    I am working on a PDF. I am trying to get the average of 3 numbers to the nearest 0.50 inch.
    So if the measurements were 16, 15, and 15 it would give the number 15.5 instead of giving the 15.33 since it is closer to 15.5 then 15.0
    Can someone help me with this problem?

    I have never done anything with Javascript before. So the values I am putting into the PDF are in field Neck1, Neck2, and Neck3. I want the average values in these 3 boxes to be put into field AvgNeck but rounded to the nearest 0.50 inch. I have tried to put your code in but I do not know how to get it to work since I don't understand how to get it to use the values I put into the fields and then get it to display. Please bare with me. I have tried to search online to see if I could figure out how to take your code and make it use my fields but i'm not currently understanding.

  • Hw to find average of numbers

    hw to find averageof numbers using sql select using the keyword as avg
    for eg:
    1+2+3+4/4
    =2.5

    with t as (select 1 b from dual union
    select 2 b from dual union
    select 3 b from dual union
    select 4 b from dual)
    select avg(b) from t

  • How do i find out my average data usage

    how do i find average monthly data, call and text usage?thank youjon 

    I'd be surprised if EE didn't keep monthly allowance averages for pay monthly accounts.  Pretty much all mobile networks usually do record this info.  I know O2 certainly do.
    Ring EE CS and see what they say.

Maybe you are looking for