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.

Similar Messages

  • Functional module for 12 MONTHS AVERAGE SALARY

    hi all,
    I want to get the average salary for an employee for past 12 months from cluster tables. I believe the cluster table for that is PCL2? . I want to know the name of the function module to get the average salary for an employee for past 12 months from cluster tables. If anyone could explain me with help of the coding how to use that function module  - passing what all parameters, it would be great.
    I anyone have any custom report for extracting payroll data from cluster tables, Please let me know. Please share the coding. My e mail id is [email protected]

    Ribhu,
    You can retrieve the last payroll result for the year & read the YTD Gross (year-to-date) from the CRT table & divide by12 to get the Average Salary..
    ~Suresh

  • 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}

  • 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.

  • Function to find quantity of a material in Open sales Order in 4.5

    hi ,
    is there any function to find the total quantity of a material in open sales order for an input date in 4.5
    Regards

    I think you may find function <b>RV_BILLING_PRINT_VIEW</b> helpful. This is the function used by the standard SAP report <b>RVADIN01</b> to assemble all the information needed to print a Sales Order. The structure and table output by this function contain all the information in the header and line items of the Sales Order.
    To watch this function in action, set a break point on this function (line 1075 of RVADIN01 in my system) and print a Sales Order (SO).
    I use VF31 to print an arbitrary SO during testing.
    Your company may have altered the standard print configuration for sales orders in SAP. If so, you will need to note the output type of your test Sales Order in VF31 and use Transaction <b>V/83</b> to determine which program is being used to print that type of SO.

  • Write two functions to find the the number of elements in a linked list?

    I am trying to Write two functions to find the the number of elements in a linked list. One method using recursion and One method using a loop...
    //The linked List class is Represented here.
    public class lp {
    public int first;
    public lp rest;
    public lp(int first1, lp rest1)
    first = first1;
    rest = rest1;
    The program i wrote so far is
    import java.util.*;
    import linklist.lp;
    public class listCount{
    //loop function
    public static void show_list(lp list)
    int counter = 0;
    while(list != null)
    list = list.rest;
    counter++;
    System.out.println ("length computed with a loop:" + counter);
    //recursive function
    public static int recursive_count(lp list)
    if (list.first == null)
    return 0;
    else
    return recursive_count(list.rest) + 1;
    //main method
    public static void main (String args[])
    lp list1 = new lp(1, new lp(2, new lp(3, null)));
    show_list(list1);
    System.out.println("length computed with a recursion:" +
    recursive_count(list1));
    at the if (list.first == null) line i get the error " incomparable types:
    int and <nulltype>" I know this is a beginners error but please
    help...What should I do?

    byte, char, short, int, long, float, double, and boolean are primitives, not objects. They have no members, you cannot call methods on them, and they cannot be set to or compared with null.

  • I updated to 7.0.1 and my search function cannot find anything now

    I updated to 7.0.1 and my search function cannot find anything now

    Searching the email. When i type in the keywords, it looks like it's searching, but the results are always the same - nothing found. I've used this function many times daily, I have an enormous amount of emails saved. Thanks...

  • Query to find Employee Salary Details

    Hi,
    Could anyone help in writing the query to find employee salary details.
    Thanks in advance.

    This should get you started:
    SELECT papf.full_name
    ,papf.email_address
    ,ppp.proposed_salary_n salary
    FROM per_pay_proposals ppp
    ,per_all_assignments_f paaf
    ,per_all_people_f papf
    WHERE ppp.assignment_id = paaf.assignment_id
    AND paaf.assignment_type = 'E'
    AND paaf.primary_flag = 'Y'
    AND paaf.person_id = papf.person_id
    AND nvl(papf.current_employee_flag, 'N') = 'Y'
    AND trunc(sysdate) BETWEEN
    ppp.change_date AND ppp.date_to
    AND trunc(sysdate) BETWEEN
    paaf.effective_start_date AND paaf.effective_end_date
    AND trunc(sysdate) BETWEEN
    papf.effective_start_date AND papf.effective_end_date;

  • Function to find cost center for pernr

    hello,
    I looke for a function to find pernr's cost centeres from infotype 0027 (not from infotype 0001).
    Thanks in advance,
    Fariba

    Hi,
    why do you need FM for that
    you can select the data directly from PA0027.
    select * from PA0027 into X_0027 where pernr = pernr
                                      and begda ge date
                                      and endda le date.
    regards
    Vijay
    Message was edited by: Vijay Babu Dudla

  • Standard function to find alphabet in string?

    Is there a standard function to find alphabet in string?
    For example, a variable define as char (10),
    I need a function to find out if this variable contains alphabet.
    Any standard function there?

    hiii
    use following code
    data: wa_str(100) type c.
    data: wa_str1 type string.
    data: wa_str2 type string.
    data: wa_str3 type string.
    data: len type i.
    data: ofset type i.
    wa_str = 'ABCD435hjK'.
    len = strlen( wa_str ).
    TRANSLATE wa_str TO UPPER CASE.
    do.
      if ofset = len.
        exit.
      endif.
    if wa_str+ofset(1) co sy-abcde  .
          concatenate wa_str2 wa_str+ofset(1) into wa_str2.
    else.
        concatenate wa_str3 wa_str+ofset(1) into wa_str3.
      endif.
      ofset = ofset + 1.
    enddo.
    write:/ wa_str.
    write:/ 'alphabatic char', 20 wa_str2.
    here TRANSLATE wa_str TO UPPER CASE.
    statement have added .i hope this will solve your problem.
    regards
    twinkal

  • HT201303 It appeared that the seller didn't disconnect function to find my iPhone and now I can make nothing with phone.

    I bought iphone 5c phone on Ebay, the seller in the description specified that phone is completely cleared and ready to work. It appeared that the seller didn't disconnect function to find my iPhone and now I can make nothing with phone. I have an invoice about purchase, I can provide the page of the transaction and screenshots from phone.
    I appealed to the seller to remove this device from the iCloud at distance, but he at all doesn't wish me to understand and speaks only about phone return, and it categorically doesn't suit me now.

    hexonxonx wrote:
    I stand by statement that the iPhone is likely stolen
    Whoopsie!
    Another reason: You said he doesn't understand that find my iPhone is activated. If the phone was originally his, he would have known what it was since he had to turn on find my iPhone to begin with.
    Doens't mean they know what FindMyiPhone is or that they even activated it.
    Many (most?)  users simply click thru without reading anything and don't have a clue what they are clicking on.

  • Function to find the greatest of two numbers

    Hi All
    In the rtf template, is there any function to find the greatest between two numbers?
    Please help
    Thanks in Advance

    Just like SQL, use the GREATEST function. List of comparable SQL functions is shown on or about page 9-30 of user guide (depends on which version you have). Search on GREATEST and you'll find it.

  • When I use the function of "finding keyword", the word would be shown in green. Can I set the colour by myself?

    When I use the function of "finding keyword"(ctrl+f), the keyword would be shown in green. I want to change the highlighted colour to be blue. Is there any function to change the colour?

    See '''''cor-el's''''' answer in this thread: https://support.mozilla.com/en-US/questions/900541
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''
    Not related to your question, but...
    You may need to update some plug-ins. Check your plug-ins and update as necessary:
    *Plug-in check --> http://www.mozilla.org/en-US/plugincheck/
    *Adobe Shockwave for Director Netscape plug-in: [https://support.mozilla.com/en-US/kb/Using%20the%20Shockwave%20plugin%20with%20Firefox#w_installing-shockwave Installing ('''''or Updating''''') the Shockwave plugin with Firefox]
    *Adobe PDF Plug-In For Firefox and Netscape: [https://support.mozilla.com/en-US/kb/Using%20the%20Adobe%20Reader%20plugin%20with%20Firefox#w_installing-and-updating-adobe-reader Installing/Updating Adobe Reader in Firefox]
    *'''''Shockwave Flash''''' (Adobe Flash or Flash): [https://support.mozilla.com/en-US/kb/Managing%20the%20Flash%20plugin#w_updating-flash Updating Flash in Firefox]
    *Next Generation Java Plug-in for Mozilla browsers: [https://support.mozilla.com/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox#w_installing-or-updating-java Installing or Updating Java in Firefox]

  • Query to find basic salary

    Hi ,
    I need to find basic salary of all the employees from their actual salary
    10% of his basic salary will be debited at the end of the month 
    If the employee is about to relieve the company ,he should be paid by 5% extra bonus from his final settlement
    How to write a query for the above scenario

    Hello,
    PFB structure and expected result
    Name  Location  Salary
    smith newyork  
    6000
    adam  dallas   
    5000
    john  delhi    
    7000
    scott laondon  
    4000
    Name  Location  Salary  Basic salary Monthly_Debit Extra Bonus
    ================================================================
    smith newyork   6000      250              25                12.5    
    adam  dallas    5000      208              20.8             10.4    
    John  delhi     7000      291              29.1             14.55
    scott laondon   4000      166              16.6             8.3

  • Oracle sql function to find VARCHAR2 data is numeric

    Hi Everyone,
    Is there oracle sql function to find whether the VARCHAR2 data is numeric?
    Thanks

    hi,
    see the below example .
    with t as
    (select '12'  as col from dual union all
    select '1 2'  as col from dual union all
    select '2 1 3'  as col from dual union all
    select 'abcde'  as col from dual union all
    select '12345'  as col from dual union all
    select '1a4A5'  as col from dual union all
    select '12a45'  as col from dual union all
    select '12aBC'  as col from dual union all
    select '12abc'  as col from dual union all
    select '12ab5'  as col from dual union all
    select '12aa5'  as col from dual union all
    select '12AB5'  as col from dual union all
    select 'ABCDE'  as col from dual union all
    select '123-5'  as col from dual union all
    select '12.45'  as col from dual union all
    select '1a4b5'  as col from dual union all
    select '1 3 5'  as col from dual union all
    select '1  45'  as col from dual union all
    select '1   5'  as col from dual union all
    select 'a  b  c  d'  as col from dual union all
    select 'a b  c   d    e'  as col from dual union all
    select 'a              e'  as col from dual union all
    select 'Steven'  as col from dual union all
    select 'Stephen'  as col from dual union all
    select '111.222.3333'  as col from dual union all
    select '222.333.4444'  as col from dual union all
    select '333.444.5555'  as col from dual union all
    select 'abcdefabcdefabcxyz'  as col from dual union all
    select 'aaa'  as col from dual union all
    select 'ddd'  as col from dual union all
    select 'ccc'  as col from dual union all
    select 'aaaaa'  as col from dual union all
    select 'aaaaaaaa'  as col from dual
    select * from t where regexp_like(col,'[1-9]')
    Result
    COL
    12
    1 2
    2 1 3
    12345
    1a4A5
    12a45
    12aBC
    12abc
    12ab5
    12aa5
    12AB5
    123-5
    12.45
    1a4b5
    1 3 5
    1  45
    1   5
    111.222.3333
    222.333.4444
    333.444.5555Thanks,
    P Prakash

Maybe you are looking for

  • Ipod Touch will not sync with Itunes 12.1.1.4 64 bit

    I have recently updated itunes and on the back of doing so my Ipod touch will not sync my library. The Ipod itself is a couple of years old but using iOS 6.1.6. I have deleted and re-installed Itunes. I have wiped my Ipod to start again. I have set i

  • MP4 won't display on apple TV - Sound is working but no pictures

    I have converted some DVD's using Handbrake Software so I can watch them on Apple TV (using Handbrake's 'normal' default output settings). After converting them I added the files to itunes. When I play these files on the Macbook they are great - all

  • Problem with scalable Flash...

    Hello all, I'm having trouble getting a Flash file to scale properly in my document: http://www.bm-group.co.uk/testspace/fandf/index.html The idea is the large central Flash file should occupy one half of the page, the solid green area with the white

  • How Do Fix Your Ipod If It Says Disabled

    What Do You Do To Fix Your Ipod When It Says Disabled?

  • Subquery referencing column in outer query

    I have a simplified problem such as... select     a.year ,     (     select     b.column           from     table b           ,     (     select     c.year                     from     table c                     where     c.year = b.year  <= ORA-009