Calculation of nth highest value in a Group

Hi All,
I have following problem to be solved. I have a table with following structure:
Table emp
EmpID number
NAme varchar2
DeptID number
Salary numberNow for finding max salary in each dept, I can use:
select DeptId,max(salary) from emp group by DeptId;NOw to find second max salary, I can do below:
select DeptId,max(salary) from emp
where (DeptId,salary) not in (select DeptId,max(salary) salary from emp group by DeptId) group by DeptId;But suppose I need to find 5th or 6th max salary then this method will be cumbersome.
I need a SQL query in which I can dynamically pass the parameter to calculate it.
Kindly help.

You could try something like this:
with ranking as
   (select
       deptid,
       salary,
       row_number() over (partition by deptid order by salary desc) rn
    from
       emp)
select
   deptid,
   salary
from
   rankings
where
   rn=4;This should get the 4th max salary for each dept having at least four employees. Maybe you should have a look at other analytic functions like rank() or dense_rank().
Hope that helps,
dhalek

Similar Messages

  • Need to take rownum highest value without using grouping functions

    Hi
    I want to display highest value in the rownum column and customer details without using grouping functions like max or count
    this below query gives me all rownum values and customer details
    SELECT ROWNUM ROWNUM_1, CUSTOMER_NO, CUSTOMER_NAME, CUSTOMER_DOJ, CUSTOMER_MOBILENO FROM CUSTOMER;
    can any one help me.

    The above query won't work as it's missing "from" cluase in the inner select statement.
    And even if corrected it willl print rownum values thrice: value "1",max_rownum, max_rownum followed by customer details.
    Below is the simple query to retrieve max row_num along with the corresponding customer details.
    select * from (SELECT ROWNUM ROWNUM_1, CUSTOMER_NO, CUSTOMER_NAME, CUSTOMER_DOJ, CUSTOMER_MOBILENO FROM CUSTOMER order by rownum_1 desc) where rownum<=1 ;

  • How to return highest/lowest value in a group of accounts?

    Hi gurus,
    I'm facing a requirement where in HFM, I need to set the value of an account to be the same as the highest value of a group of other accounts (POV is the same, all accounts are lowest level in hierarchy).
    So basically, I need a rule/script/function that enables me to say: "look up the values of account 1, account 2 and account 3 for this point of view, and set the value of account 4 to be whatever is the highest of the values of accounts 1, 2 and 3".
    I would be extremely grateful for any insights and assistance. I'm sure this is possible in VBScript....
    br
    Samuli

    Indeed this is possible in VBScript.
    You don't have handy Max/Min functions in VBscript but given that you've only got three inputs, you can easily compare one number against the other two and deduce the maximum from there.
    First of all, get the data from the 3 intersections you want using GetCell
    Var1 = HS.GetCell("POVExpression")
    Var2 = HS.GetCell("POVExpression")
    Var3 = HS.GetCell("POVExpression")
    Then do a simple comparison of the three values using something like below
    If Var1 >= Var2 And Var1 >= Var3 Then
    VarMax = Var1
    ElseIf Var2 >= Var1 And Var2 >= Var3 Then
    VarMax = Var2
    Else
    VarMax = Var3
    End If
    The maximum value will be in the variable VarMax. You can now use HS.Exp to to assign that variable to the desired account

  • Function module that can give the last value or the highest value of a key

    hi,
    Is there any function module that can give the last value or the highest value of a key feild in a z table.
    regards,
    johnson

    Hi ,
    We have  aggregate functions in SQL. Some of the functions are as follows.
    MAX(col ) Determines the maximum value of the value in the column col in the resulting set or in the current group.
    MIN( col ) Determines the minimum value of the content of the column col in the resulting set or in the current group.
    AVG(  col ) Determines the average value of the content of the column col in the resulting set or in the current group. The data type of the column has to be numerical.
    SUM( col ) Determines the sum of the content of the column col in the resulting set or in the current group. The data type of the column has to be numerical.
    COUNT( col ) Determines the number of different values in the column col in the resulting set or in the current group.
    For further details , type the function name name and press F1 for further help.
    Eg: select count(mantr) from mara into workarea where condition.
    Reward points if helpful.
    Thanks and Regards.

  • Finding nth highest salary

    Hi guys , I am trying to find the nth highest salary
    using the below query , is there any case in which the below query can fail
    select
    * from (
    select
    distinct rownum rn,salary from emp_mgr order by rownum) t where t.rn=3

    chris227 wrote:
    Sory, may be i am blind, dont see it yet.
    Doesnt the Nth high paid employee earns the Nth highest salary?
    No. Multiple employees can earn same salary. Look at EMP table:
    SQL> select ename,sal from emp order by sal desc;
    ENAME             SAL
    KING             5000
    FORD             3000
    SCOTT            3000
    JONES            2975
    BLAKE            2850
    CLARK            2450
    ALLEN            1600
    TURNER           1500
    MILLER           1300
    WARD             1250
    MARTIN           1250
    ENAME             SAL
    ADAMS            1100
    JAMES             950
    SMITH             800
    Highest salary 5000. Second highest salary is 3000. Third highest salary is 2975. Now look what NTH_VALUE returns:
    SQL> select distinct sal
      2    from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
      3  /
    Enter value for n: 1
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,1) over(order by sal desc) sal from emp)
           SAL
          5000
    SQL> /
    Enter value for n: 2
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,2) over(order by sal desc) sal from emp)
           SAL
          3000
    SQL> /
    Enter value for n: 3
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,3) over(order by sal desc) sal from emp)
           SAL
          3000
    SQL> /
    Enter value for n: 4
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,4) over(order by sal desc) sal from emp)
           SAL
          2975
    SQL>
    SY.

  • Finding max() within a max() or highest value in 1row-1col w. multi-value

    Hi,
    I am trying to get a result set that has following criteria
    - for rows using the same WEL_FK column, I'd like the latest date
    and within the latest date the highest weight. (Sort of a max() within a max()) for each WEL_FK).
    -if there is a row that has no other matching WEL_FK;s (like row 8)
    it should still return that row.
    PER_PK WEL_FK A_DATE WEIGHT
    1 1 2010-10-22 4
    2 1 2010-11-23 4
    3 1 2010-10-22 6
    4 3 2010-10-22 2
    5 3 2010-11-23 2
    6 3 2010-10-22 2
    7 4 2010-10-22 5
    8 6 2010-10-22 5
    9 6 2010-10-21 6
    10 6 2010-10-22 4
    10 rows selected.
    RESULTS desired
    PER_PK WEL_FK A_DATE WEIGHT
    2 1 2010-11-23 4 because it has the latest date within same foreign key even if wt. not the highest
    5 3 2010-11-23 2 because it has the latest date within same foreign key, wts. are equal
    7 4 2010-10-22 5 because there are no other rows with that WEL_FK
    8 6 2010-10-22 5 because it has latest date with highest wt.
    I am able to get close to what I want using the SQL below which gives me correct rows
    but does not tell me the "weight" nor "PER_PK" column.
    I have been trying to find a way to pick highest value from 1 ROW and within 1 column
    with multiple-values but think I have dug myself into a hole.
    When I add in the PER_PK above, it gives me of course all 10 rows again.
    SELECT wel_fk,
    LTRIM(MAX(SYS_CONNECT_BY_PATH(a_date,','))
    KEEP (DENSE_RANK LAST ORDER BY curr),',') AS employees
    FROM (SELECT wel_fk,
    a_date,
    ROW_NUMBER() OVER (PARTITION BY wel_fk ORDER BY a_date) AS curr,
    ROW_NUMBER() OVER (PARTITION BY wel_fk ORDER BY a_date) -1 AS prev
    FROM test)
    GROUP BY wel_fk
    CONNECT BY prev = PRIOR curr AND wel_fk = PRIOR wel_fk
    START WITH curr = 1;
    WEL_FK EMPLOYEES
    1 2010-10-22,2010-10-22,2010-11-23
    3 2010-10-22,2010-10-22,2010-11-23
    4 2010-10-22
    6 2010-10-21,2010-10-22,2010-10-22
    ==========================================================
    I have been exploring analytics, connect by's, subqueries, wm_concat, SYS_CONNECT_BY_PATH ,etc. along with max()for days and get real close
    but somehow it's off.
    If you are able to provide actual SQL solution, ideally using what I have already, would be appreciated.
    Thanks.
    the_sql

    Try this:
    WITH src AS (
    SELECT per_pk,
           wel_fk,
           a_date,
           weight,
           MAX( a_date ) OVER (PARTITION BY wel_fk ORDER BY a_date
                      RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) latest_date,
           last_value( weight ) OVER (PARTITION BY wel_fk ORDER BY a_date, weight 
                      RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) max_weight
    FROM TEST
    SELECT per_pk,
           wel_fk,
           a_date,
           weight
    FROM src
    WHERE a_date = latest_date
         AND weight = max_weight
    PER_PK                 WEL_FK                 A_DATE                    WEIGHT                
    2                      1                      2010/11/23                4                     
    5                      3                      2010/11/23                2                     
    7                      4                      2010/10/22                5                     
    8                      6                      2010/10/22                5       

  • How to add only highest values in the column

    Hello All,
    We have report where I need to add only highest values in 'Price' column.
    Ex:
    Group  Mat      Price
    Grp1    Mat1    50
               Mat2    75
               Mat3    100
    Grp2    Mat1    50
               Mat2    100
    I need my result as 200...
    Any input is appreciated!
    Thanks in advance !!
    Venu.

    Sriman/Surendra,
    Unfortunately, this approach does not work because the Calculate Result As --> Maximum applies not only to the subtotals but also to the grand total. Therefore, the result in Venu's example will be:
    MAX(Grp1) = 100
    MAX(Grp2) = 100
    MAX(All Grps) = 100
    We have the same requirement as Venu, but have not found a satisfactory solution yet. The only way we have solved such problems in the past is to use VBA in workbooks, but the report we are using now is a Web report.
    Hope this helps to clarify the issue...
    Bob

  • Nth Highest Salary from EMP table , need explaination

    I am new to the database world and hence learning queries at the initial stages. I want to retrieve the nth highest salary from the EMP table. I was not able to find out the answer by myself , so I searched on google. The following was the answer i got :
    SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
    Enter value for n: 2
    SAL
    3700
    Suppose the table contains salary in the following order :
    SAL
    2000
    3000
    3700
    4000
    3700
    2000
    So how come I will get the correct answer with the abov query ? I am not able to understand the part --- WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
    Specially the condition WHERE a.sal<=b.sal is very confusing to me. Can anyone help me please to understand the same.

    user12328699 wrote:
    I am new to the database world and hence learning queries at the initial stages. I want to retrieve the nth highest salary from the EMP table. I was not able to find out the answer by myself , so I searched on google. The following was the answer i got :
    SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
    Enter value for n: 2
    SAL
    3700
    Suppose the table contains salary in the following order :
    SAL
    2000
    3000
    3700
    4000
    3700
    2000
    So how come I will get the correct answer with the abov query ? I am not able to understand the part --- WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
    Specially the condition WHERE a.sal<=b.sal is very confusing to me. Can anyone help me please to understand the same.There is many better way to get the nth highest salary
    But still if you want to understand the same.
    Assuming the data is sorted in ascending order, then
    1) a.sal=2000, so a.sal<=b.sal results in count as 3 (not equal to user input)
    2) a.sal=3700, so a.sal<=b.sal results in count as 2 (equal to user input)
    3) a.sal = 4000 , so a.sal<=b.sal results in count as 1 (not equal to user input)
    Hence the answer is 3700
    Regards
    Anurag

  • How can we select the highest value from 3 disfferent #defined values???

    Hello,
    Sometimes I come across the requirement of having the program automatically select the highest value
    among several defined preprocessor command statements. For example:
    #include "stdio.h"
    #include <math.h>
    #define _K_BUF_OTHERS 20
    #define _k_BUF_ENV_TAGS 30
    #define _k_BUF_REGS 40
    #define _k_MAX(x, y, z) (max((max(x, y)), z))
    int main(){
    unsigned int u;
    u = _k_MAX(_k_BUF_OTHERS,_k_BUF_ENV_TAGS, _k_BUF_REGS);
    return 0;
    In the sample above we have three (3) different define statements called :
    _k_BUF_OTHERS
    _k_BUF_ENV_TAGS
    _k_BUF_REGS
    but at any given time in certain C modules (In this case above, the main.c module) I require for the program to know
    which of the three is the highest and get that highest value so I can use it downstream of my code. In this case the highest would be 40. So therefore putting the following macro anywhere in my code should make a text substitution of the macro's value
    and return 40 to u:
    u = _k_MAX(_k_BUF_OTHERS, _k_BUF_ENV_TAGS, _k_BUF_REGS);
    But I can't even compile the program!
    Here's the error I get in VC++:
    1>------ Build started: Project: MinMax, Configuration: Debug Win32 ------
    1>  Source1.cpp
    1>c:\c++_tests\minmax\minmax\source1.cpp(15): error C3861: 'max': identifier not found
    1>c:\c++_tests\minmax\minmax\source1.cpp(15): error C3861: 'max': identifier not found
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    Can someone please have a look and see what I am doing wrong.
    All help appreciated...
    Thanks
    r

    On 4/12/2015 4:30 PM, roberto wrote:
     1>c:\c++_tests\minmax\minmax\source1.cpp(15): error C3861: 'max': identifier not found
    So implement or #define one. C standard library doesn't provide a function named "max".
    Igor Tandetnik

  • Error while calculating the net present value

    Dear experts,
    Please help me in solving the following error.
    I am trying to do project vaibility analysis through pre investment analysis in appropriation request, interm I'm trying to calculate the IRR for the project.
    I have created the appropriation request and given all the data in that including the planed values for the project.
    In Variants tab of appropriation request, preinv. analysis sub tab, i have clicked the button Calculate preinvestment analysis figures , ( I hvae not mentioned any values in that screen, its picking the plan cost from the planed values of the appropriation request) there I'm getting an error saying
    Error while calculating the net present value
    If I open the message it is as follows:
    Error while calculating the net present value*
    *Message no. AO215*
    Diagnosis
    An error occurred during calculation of the net present value.
    The yield curve for determining the net present value is not completely maintained. Possible causes are:
    1. Evaluation type IM01 does not exist (table ATSYC).
    2. Yield curve types 9990 (bid) and 9991 (ask) have not been created (table JBD14) for the currency of the controlling area of the appropriation request.
    3. Reference interest rates have not been created for the yield curves (tables T056R and JBD15).
    4. Interest rates are not maintained for the complete planning time period for the reference interest rates.
    5. Under certain circumstances, the standard exchange rate types 'G' and 'B' may be inconsistent.
    Procedure
    Check your Customizing settings:
    1. SAP supplies the evaluation types.
    Remember, SAP supplies the evaluation types in client 000. You have to copy them into your working clients. If you do not have them in your system, you can create them in Customizing for the Treasury component (Treasury Management -> Market Risk Management -> Evaluations -> Define Default Settings). Create evaluation type IM01 with bid yield curve type 9990 and ask yield curve type 9991.
    2. In Customizing for appropriation requests (under Planning), create a bid yield curve type 9990 and an ask yield curve type for the currency of the controlling area of the appropriation request.
    3. Create at least one reference interest rate for each yield curve.
    4. Maintain the reference rates, starting at the minimum fron the point at which you you have planned costs or revenue.
    5. Check Customizing of the exchange rate types 'G' and 'B' in the IMG under Global Settings -> Currencies.
    I have checked all the procedures of the said customization and the values are similar to that of the error message, but still I'm unable to proceed further.
    I have goe through the note 160375, but did not succeed on this issue.
    Can any one help me out in solving the above error and also can any one explain me the process in SAP to calculate IRR?
    Is there any more customization missing or whats wrong going in that process?
    Please help me out...
    Thanks in advance..
    Regards,
    Praveen.

    Are you installing a Demo version of NetWeaver? If so please post your questions and search for answers here: SAP NetWeaver Application Server
    If this a real full blown system please contact the OSS, via the Marketplace (service.sap.com) or by OSS transaction in your SAP System.

  • The default value of purchasing group in "carry out Sourcing "

    Dear , expert :
         I work in SRM7.0 ,ECS!
       I have two questions about the screen of    "carry out Sourcing ":
    1,How can set the default value of purchasing group ?Now the default is empty .
    2.The purchaser can select many purchaser group here ,I want to know what controls this .in the group responsibility ?
    Thanks!

    Hi Alex
    If there are more purchase group responsible for one product category. the end user (requestor) can select which purchase group before he order a cart.
    so that sc goes to respective purchaser cockpit  in the sc ?
    if you have only one purchase group responsible . no probem
    or
    redistribute workload
    you can distribute your cart to another purchaser
    for eg. initailly ALEX is purchase group in the sc.
    now you can transfer MASA purchase group  via redistribution workload
    so now the sc shows in the MASA cockpit with new purchase group as MASA instead of ALEX purchase group name
    br
    muthu

  • Can you set default values for person/group picker fields? To current user?

    Two-part question/issue . . .
    Part 1:
    In InfoPath 2013 in use with SharePoint 2013, how do you set a Default Value for Person/Group Picker fields? Other field types like Text Boxes have a Default Value section in the Data tab of Properties.  There doesn't appear to be any equivalent for
    the Person/Group Picker field type in Properties.  I'd like to set a default person for a few fields in a form I've created.  Is this possible?
    Part 2:
    The default user I want to set for one of those Person/Group fields is the "current user."  I want a user to log into our SharePoint 2013 intranet, load a new form for edit/creation, and have one of the Person/Group fields in that form to
    automatically populate this particular user.  Is this possible?

    Hi Stephen,
    You can auto populate your InfoPath farm with current user Name and all other property that you have in your User profile, you have couple of options.
    First you can make a secondary connection in your InfoPath form with user profile and can use the UserProfileService.asmx and call the GetUserProfileByName method. Here is the steps you can follow.
    http://blogs.technet.com/b/anneste/archive/2011/11/02/how-to-create-an-infopath-form-to-auto-populate-data-in-sharepoint-2010.aspx
    Secondly you can use JQuery and SPServices ,
    $().SPServices.SPGetCurrentUser function to populate the values with script to achieve the same in this case you no need to use InfoPath form just create simple text type column in SharePoint
    list and auto populate it with getting the current user Name from User Profile here is the scripts
    <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery-1.4.2.min.js"></script>
    <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery.SPServices-0.5.4.min.js"></script>
    <script language="javascript" type="text/javascript">
    $(document).ready(function() {
      var userCurrentName = $().SPServices.SPGetCurrentUser({
        fieldName: "CurrentUser"
      $("input[Title='CurrentUser']").val(userCurrentName);
      var userPhone = $().SPServices.SPGetCurrentUser({
        fieldName: "WorkPhone"
      $("input[Title='Phone']").val(userPhone);
    </script>
    Krishana Kumar http://www.mosstechnet-kk.com

  • How to set Default Value in People Group KFF

    Hi
    We are storing some information in People Group KFF which depends on Employee Category so if employee category is Permanent Headcount then the value in People group KFF will be different and if it is Temporary then the value will be different.
    Now we want to default the People Group KFF value automatically based on Employee Category for a New Hire employee. And also we should be able to change the People Group KFF value for some new hire as there are few exceptions.
    I tried WHEN-NEW-RECORD-INSTANCE and tried to set the value through INITIAL_VALUE but it is not working.
    Kindly please advise if you have idea on how to implement this requirement.
    Thanks
    Gaurav

    Hello Gaurav,
    If I understood correctly, Your requirement is to update People Group segments based on employee category.
    Basically you need to update people group values based on employee category before insert into assignment table.
    You can acheive this using Dynamic Trigger on Assignment Table.
    you need to change the new.people_group_id along with other segment values in this trigger logic.
    Following articles will help you steps on how to create dyanamic triggers.
    http://oracle.anilpassi.com/dynamic-triggers-in-hrms-payroll-demo.html
    http://apps2fusion.com/apps/oracle-hrms/oracle-hr/204-triggers-in-oracle-hrms-and-payroll
    Regards,
    Saurabh

  • RE:calculated Average Valuated Stock Value

    Hi ALL,
    how to calculated Average Valuated Stock Value  logic (The sum of the daily stock value for the time frame of the analysis divided by the number of days) please guide me.
    regards,
    ravi

    Please ...........................
    guide me.......................
    how to created formula for this logic
    (The sum of the daily stock value for the time frame of the analysis divided by the number of days)
    Regards,
    ravi

  • Highest values

    Can any one help me in coding ,to find the 3 highest values from an array.

    Preethi_Raja wrote:
    hi thanks
    Actually we are developing a project for a telescope.
    My program has an array of intensity values(i.e The pixel values of the image taken from the telescope)
    The highest value means the brightest source or point.
    Now my program needs to find three brightest point from an image.Start by thinking of how /you/ would solve the problem. If I gave you 100 numbers, and asked you to find the three highest, how would you proceed to do that? How would you then (generically) tell a computer to do this? And finally, how would you do this in Java?

Maybe you are looking for

  • Proxy upgrade from SP1 to SP5 doesn't work anymore for virus scanning.

    Upgraded from SP1 to SP5 and the virus scanning updates no longer work. No changes have been made it is a complete carbon copy using the migrate button. No ip addresses have been altered nor has the ports been changed. I've tried SP2, 3 & 4 and they

  • MVA SQL Server Query Assessment question

    Hi Guys I was doing a course on MVA, Querying Microsoft SQL Server Quick Start. This question came up in the assessment: True or False: You use the INTERSECT operator to combine results from two SELECT statements. Only rows that appear in both result

  • How to set a customized search results template for all users

    Hi. I know the customized search results views are stored in a file called pne_portal.hda that resides on every user's subfolder in data/users/profiles/... Is there a way to set a customized search results template for all users? If it's impossible,

  • PSA about Verizon Edge Buyout

    This is not clear on the the website and I only found out by calling Customer Service. BACKGROUND: In MyVerizon you can view your VerizonEdge contract via a pop-up box. You see the amount financed and your VerizonEdge balance.  Also displayed is the

  • HT1766 Password for restoring from backup

    After updating my iphone to the new ios software it crashed now it is asking me to enter in a password to restore from the backup I did earlier today however I didn't get prompted to enter in a password. therefore how to I find out what my password i