How to retrieve 5th highest salary in a single statement

Hi,
How can we retrieve 5th highest salary in a single statement

Another method
select top 1
 OrderID
, Quantity
from
 select top 5
  OrderID
 , Quantity = sum (Quantity)
 from
  [Order Details]
 group by
  OrderID
 order by
  2 desc
) q
order by
 2  asc
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • 2nd and 5th highest salary

    hi, i am kind of new to sql. i have a table with employee name and salary.
    i would like to find the name of the 2nd highest salary? also i like to get the name of the 5th highest salary
    here is my data
    INSERT INTO er4 VALUES('john', 1000, 123);
    INSERT INTO er4 VALUES('john2', 3000, 234);
    INSERT INTO er4 VALUES('john3', 1000, 223);
    INSERT INTO er4 VALUES('john4', 4000, 123);
    INSERT INTO er4 VALUES('john5', 8000, 023);
    INSERT INTO er4 VALUES('john6', 9000, 023);
    INSERT INTO er4 VALUES('john7', 8000, 723);
    you can see in the data that there are two employee with highest second salary. i would like to get either one but i want my query to return one row
    can somebody help me write a query to get the name and salary of 2nd highest and name and salary of 5th highest

    Hi,
    Part of learning about functions is learning what they are good for, and what they are not good for.
    As Justin said, MAX is not good for this task.
    If you were interested in just the 1st highest salary, you possibly could use MAX like this:
    SELECT  *
    FROM    er4
    WHERE   salary  =      (
                   SELECT     MAX (salary)
                   FROM     er4
    AND     ROWNUM     = 1     -- in case of a tie, pick one row arbitrarily
    ;But even if the goal was to find the highest salary, I would use ROW_NUMBER, like Justin did.
    Why? The following scenario happens all the time in real life. The client for whom you wrote this comes back in 3 months and says: "That query you wrote for the highest salary works great! We've found it so useful, we'd like to do something similar to find the 2nd highest salary, or the 5th highest, or the top 5, or the next 5." ROW_NUMBER is flexible enough to do all these things. When you have to solve one problem, you'll save time (in the long run) if you can foresee, or just guess, what similar problems you might need to solve later, and write something for today's problem that can easily be adapted for tomorrow's potential problem.

  • How to concatenate all the fields in a single statement with tilda..

    hi, i have 10 fields, i have to concatenate those fields seperated with tilda... and put into the application server...in a single statement,
    kindly suggest me hw to write..?
    Thanx in Advance.
    Akshitha.

    Hi.....
    Just see the following code...
    It solves your requirement.....
    REPORT  ZCSV_SPFLI_APP.
    TABLES :
      SPFLI.                               " Flight
      FIELD-SYMBOLS : <FS>. "TYPE C.
    DATA T_SPFLI LIKE STANDARD TABLE OF SPFLI .
    DATA W_CHAR(20) TYPE C.
    DATA W_TYPE .
    DATA:
      BEGIN OF T_TABLE OCCURS 0,
        LINE TYPE STRING,
      END OF T_TABLE.
    SELECT * FROM SPFLI INTO TABLE T_SPFLI.
    LOOP AT T_SPFLI INTO SPFLI.
      DO.
        ASSIGN COMPONENT SY-INDEX OF STRUCTURE SPFLI TO <FS>.
        IF SY-SUBRC NE 0.
          EXIT.
        ELSE.
          MOVE <FS> TO W_CHAR.
          IF SY-INDEX EQ 1.
            T_TABLE-LINE = <FS>.
          ELSE.
            CONCATENATE T_TABLE-LINE '~' W_CHAR INTO T_TABLE-LINE.
          ENDIF.
        ENDIF.
      ENDDO.
      CONDENSE T_TABLE-LINE.
      APPEND T_TABLE.
    ENDLOOP.
    LOOP AT T_TABLE.
      WRITE / T_TABLE-LINE.
    ENDLOOP.
    OPEN DATASET 'YH647_SPFLI' FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
    IF SY-SUBRC NE 0.
      MESSAGE ' File is Not Opend' TYPE 'S'.
    ENDIF.
    LOOP AT T_TABLE.
      TRANSFER T_TABLE-LINE TO 'YH647_SPFLI'.
    ENDLOOP.
    CLOSE DATASET 'YH647_SPFLI'.
    This reads flight detail and makes the separated by '~' and  stores in the application server (<b>OPEN_DATASET, TRANAFER , CLOSE DATASET</b>)
    Reward points if useful.........
    Suresh........

  • Pls help me in finding highest salary of employee.

    can anybody give me...
    the general query...for finding out nth highest salary of the employee in a particular department.....
    for example, if i want to find out 2nd highest salary or some 5th highest salary of the employee.....
    i want query with a littlebit explanation also...

    i
    cannot do the sumation of those value then the
    negative value that being re-enter become 0. how can
    i make the value to become another positive value?Are you doing the `sumation' during the data entry (loop)? If so, make sure you only include valid value in the count (i.e. positive integers).

  • How to get highest salary from salary column in sharepoint list

    Hello,
    I have one custom list in which there is one salary column so I want to get the highest salary.Can we do this OOTB or by using custom code by adding webpart(using CAML query).
    Thanks,

    http://stackoverflow.com/questions/516073/max-query-using-caml
    <Query>
    <OrderBy>
    <FieldRef Name="particularcolumn" Ascending="FALSE" />
    </OrderBy>
    </Query>
    http://stackoverflow.com/questions/8383616/caml-query-on-a-sharepoint-2010-list
    http://sharepoint.stackexchange.com/questions/16955/how-to-select-max-field-in-caml-query
    If this helped you resolve your issue, please mark it Answered

  • How to find the third highest salary by distinct the salary from deptno20,from employee table

    how to find the third highest salary by distinct the salary from deptno20,by using employee table

    You already asked this question, a half hour earlier:
    https://forums.oracle.com/thread/2569985
    and received a reply.
    Do not multi-post to the forums.
    These are user-to-user forums and everyone is posting because they volunteer to post and not because they get paid to post.    Everyone else is paid exactly the same as you are paid to post here.   When you multi-post is makes you appear as impatient and expecting instantaneous answers.
    That is poor forum etiquette, approaching behavior similar to spamming the forums.
    This duplicate post is locked.

  • How to find the third highest salary from deptno20,from employee table

    how to find the third highest salary from deptno20,from employee table

    SELECT *
      FROM emp;
    EMPNO
    ENAME
    JOB
    MGR
    HIREDATE
    SAL
    COMM
    DEPTNO
    7369
    SMITH
    CLERK
    7902
    12/17/1980
    1000
    3
    20
    7499
    FEDERAL
    SALESMAN
    7654
    2/20/1981
    2000
    4
    30
    7521
    WARD
    SALESMAN
    7698
    2/22/1981
    3000
    4
    30
    7566
    JONES
    MANAGER
    7839
    4/2/1981
    4000
    3
    20
    7839
    MARTIN
    SALESMAN
    7698
    9/28/1981
    5421
    4
    30
    7698
    BLAKE
    MANAGER
    7698
    5/1/1981
    6222
    4
    30
    7782
    CLARK
    MANAGER
    7839
    6/9/1981
    5222
    2
    10
    7788
    SCOTT
    ANALYST
    7566
    12/9/1982
    5463
    3
    20
    7839
    KING
    PRESIDENT
    7902
    11/17/1981
    8543
    2
    10
    7844
    TURNER
    SALESMAN
    7698
    9/8/1981
    2124
    4
    30
    7876
    ADAMS
    CLERK
    7788
    1/12/1983
    2125
    3
    20
    7900
    JAMES
    CLERK
    7698
    12/3/1981
    5462
    4
    30
    7902
    FORD
    ANALYST
    7566
    12/3/1981
    2132
    3
    20
    7934
    MILLER
    CLERK
    7782
    1/23/1982
    5165
    2
    10
    SELECT sal, deptno
      FROM (SELECT   a.*,
                     DENSE_RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) r
                FROM emp a
          ----  ORDER BY sal DESC
    WHERE r = 3;
    SAL
    DEPTNO
    5421
    30
    5165
    10
    2132
    20
    Regards ,
    Friend
    Message was edited by: MostWanted!!!!

  • How to find record having second highest salary

    Hello friends
    I ve a table empsal
    it has 2 columns name,salary
    i need to find out name of employee with second highest salary.
    how shud i ..pls help...
    thks
    sonal...

    in the doc
    create or replace type SecondMaxImpl as object
      max NUMBER, -- highest value seen so far
      secmax NUMBER, -- second highest value seen so far
      static function ODCIAggregateInitialize(sctx IN OUT SecondMaxImpl)
        return number,
      member function ODCIAggregateIterate(self IN OUT SecondMaxImpl,
        value IN number) return number,
      member function ODCIAggregateTerminate(self IN SecondMaxImpl,
        returnValue OUT number, flags IN number) return number,
      member function ODCIAggregateMerge(self IN OUT SecondMaxImpl,
        ctx2 IN SecondMaxImpl) return number
    create or replace type body SecondMaxImpl is
    static function ODCIAggregateInitialize(sctx IN OUT SecondMaxImpl)
    return number is
    begin
      sctx := SecondMaxImpl(0, 0);
      return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT SecondMaxImpl, value IN number) return number is
    begin
      if value > self.max then
        self.secmax := self.max;
        self.max := value;
      elsif value > self.secmax then
        self.secmax := value;
      end if;
      return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self IN SecondMaxImpl,
        returnValue OUT number, flags IN number) return number is
    begin
      returnValue := self.secmax;
      return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self IN OUT SecondMaxImpl, ctx2 IN SecondMaxImpl) return number is
    begin
      if ctx2.max > self.max then
        if ctx2.secmax > self.secmax then
          self.secmax := ctx2.secmax;
        else
          self.secmax := self.max;
        end if;
        self.max := ctx2.max;
      elsif ctx2.max > self.secmax then
        self.secmax := ctx2.max;
      end if;
      return ODCIConst.Success;
    end;
    end;
    CREATE OR REPLACE FUNCTION SecondMax (input NUMBER) RETURN NUMBER
    PARALLEL_ENABLE AGGREGATE USING SecondMaxImpl;
    SELECT deptno,SecondMax(sal)
    FROM emp
    GROUP BY deptno;
        DEPTNO SECONDMAX(SAL)
            10           2450
            20           3000
            30           1600

  • How will i get the n'th highest salary????????

    Hi
    plz can anybody tell me the query to find nth highest salary from emp table???
    Thanx
    Gagan

    try this
    SELECT employee_name, salary,
           RANK() OVER (order by salary) AS ranking
    FROM   employee) empor to get the particular ranking
    SELECT emp.employee_name, emp.salary
    FROM
         (SELECT employee_name, salary,
                 RANK() OVER (order by salary) AS ranking
          FROM   employee) emp
    WHERE emp.ranking = <rank number>

  • 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 to retrieve the max value from a cursor in procedure

    Hi,
    In a procedure, I defined a cursor:
    cursor c_emp is select empno, ename, salary from emp where ename like 'J%';
    but in the body part, I need to retrieve the max(salary) from the cursor.
    could you please tell me how I can get the max value from the cursor in the procedure.
    Thanks,
    Paul

    Here is one sample but you should just get the max directly. Using bulk processing should be a last resort.
    DECLARE
      CURSOR c1 IS (SELECT * FROM emp where sal is not null);
      TYPE typ_tbl IS TABLE OF c1%rowtype;
      v typ_tbl;
      max_sal number;
    BEGIN
      OPEN c1;
      max_sal := -9999999999999;
      LOOP                                                 --Loop added
        FETCH c1 BULK COLLECT INTO v LIMIT 3; -- process 3 records at a time
            -- process the records
           DBMS_OUTPUT.PUT_LINE('Processing ' || v.COUNT || ' records.');
            FOR i IN v.first..v.last LOOP
                 if v(i).sal > max_sal then
                   max_sal := v(i).sal;
                 end if;
                DBMS_OUTPUT.PUT_LINE(v(i).empno);
            END LOOP; 
        EXIT WHEN c1%NOTFOUND;
      END LOOP;
      DBMS_OUTPUT.PUT_LINE('Max salary was: ' || max_sal);
    END;
    Processing 3 records.
    7369
    7499
    7521
    Processing 3 records.
    7566
    7654
    7698
    Processing 3 records.
    7782
    7788
    7839
    Processing 3 records.
    7844
    7876
    7900
    Processing 2 records.
    7902
    7934
    Max salary was: 5000

  • I have lost all my notes data after restore. Anyone know how to retrieve notes after restore?

    I have lost all my notes data after restore. Anyone know how to retrieve notes after restore?
    I havent' took any backup of my notes in icloud. The moment I enter the password after restore my notes will be empty. The only option to get notes back is that after restore skip entering icloud password. But any time I enter icloud password anywhere again my notes will be empty. I have huge data saved in my notes. Apple need to look into this issues very seriously. This is the 5th time I restoring my iphone today just to get my note back.

    I have the issue with losing all my notes and I don't even know why.  I can't remember changing any email account info.  What happened to them?
    Ipad 3rd io7
    Please Help!
    Thank you,
    S.

  • How to retrieve the value of last identity has been updated in a database?

    how to retrieve the value of last identity has been updated in a database

    Hi,
    Oracle 10g, FGA - Fine grained auditing, supports DML statements (9i only select).
    Set up FGA using the DBMS_FGA.ADD_POLICY procudure:
    sql> BEGIN
    DBMS_FGA.ADD_POLICY (
    policy_name => 'AUD_EMPLOYEE_SAL',
    object_schema => 'HR',
    object_name => 'EMPLOYEE',
    audit_column => SALARY',
    audit_condition => '',
    statement_type => 'UPDATE');
    END;
    NEXT:
    sql> SELECT dbuid, lsqltesxt FROM sys.fga_logs$;
    The database inserts the audit record into the FGA_LOG$ table using an autonomous transaction; even if you roll back the update statement, the update action will still be logged in this table. The fga_log$ tracks the session, machine id, timestamp, schema, scn, etc:
    SQL> desc fga_log$
    Name Null? Type
    SESSIONID NOT NULL NUMBER
    TIMESTAMP# DATE
    DBUID VARCHAR2(30)
    OSUID VARCHAR2(255)
    OSHST VARCHAR2(128)
    CLIENTID VARCHAR2(64)
    EXTID VARCHAR2(4000)
    OBJ$SCHEMA VARCHAR2(30)
    OBJ$NAME VARCHAR2(128)
    POLICYNAME VARCHAR2(30)
    SCN NUMBER
    SQLTEXT VARCHAR2(4000)
    LSQLTEXT CLOB
    SQLBIND VARCHAR2(4000)
    COMMENT$TEXT VARCHAR2(4000)
    PLHOL LONG
    STMT_TYPE NUMBER
    NTIMESTAMP# TIMESTAMP(6)
    PROXY$SID NUMBER
    USER$GUID VARCHAR2(32)
    INSTANCE# NUMBER
    PROCESS# VARCHAR2(16)
    XID RAW(8)
    AUDITID VARCHAR2(64)
    STATEMENT NUMBER
    ENTRYID NUMBER
    DBID NUMBER
    LSQLBIND CLOB
    SQL> spool off

  • ABAP Query to display top 5 employees who are having highest salary

    How will you write a query in abap to display top 5 emplyeee records who are having Highest Salary Among all the employees.
    Please Reply...

    Hi Kush,
    Before writing any Database Query, always keep 2 important thumb rules in your mind :
    1. Keep the number of data base access small
    2. Keep the amount of data transfer small.
    As you mentioned the Database Table has only 100 records, you can locally buffer the Table. So, make a local buffering and then you can sort the table based on the salary.
    Select *
      from Table_name
    into table gt_itab.
    Sort gt_itab by salary descending.
    Now you can read the  entries one after the another based on the index.
    Have a look at the following code for an efficient performance feature. Goto SE38 and have a look at the ABAP Examples.
    demo_select_some_columns. Package : SABAPDEMOS
    Hope this will help.
    Thanks,
    Samantak.

  • To find 2nd highest salary in employee table

    Hi,
    I want to know how to calculate the 2nd highest salaried employee details.
    rownum "=" sign cannot be used i suppose and
    with and without using orderby clause.
    both the methods needed.
    cheers,

    With order by
    select * from
       ( select q.*, rownum as rn from
          ( select * from emp order by sal desc ) q
    where rn=2
    /With analytics:
    select empno , sal
    from ( select empno , sal
                  , dense_rank () over (order by sal desc) as sal_rank
           from emp )
    where sal_rank = 2Notice that DENSE_RANK() might give us a different result compared to RANK() and both give us a different result from the first example.
    Cheers, APC

Maybe you are looking for

  • Nokia C5-03 and Mac OSX Lion - Problems copying files to phone in Mass Storage mode

    Whenever I try to load more than one file from my iMac (early 2008, OSX Lion 10.7.2) to my new Nokia C5-03 in Mass Storage mode -since the files are MP3s and Multimedia Transfer doesn't seem to work at all, I keep on getting asked which transfer mode

  • Apple ID displayed on iMessage

    Hi all, When I use iMessage to another iPhone user, I was told it was my Apple ID that was displayed, instead of my phone number.  We are on each other's contact lists but do not exchange email address.  Is there anyway to prevent my Apple ID disclos

  • Creator Early Access SDK Level

    Hi I downloaded Sun Java Studio Creator 2 Early Access 2. Now I tried to set the source level to 1.5 to support tiger but it always go back to 1.4. Below is how I set the source level to JDK 1.5: I select the project and right click to select propert

  • ITunes doesn't recognise iPod as the default player for audio files.

    A few weeks ago my husband completely re-installed our laptop, without properly looking at how to backup my iPod touch. Everything was lost and I have had to start again, however the system still comes up with this message each time I plug the iPod i

  • "iTunes is updating..." but it's frozen!

    I have just acquired my first iPhone as a hand-me down from my son. Connected to iTunes via my computer running Mavericks 10.9.2. I started the process of updating the software to iOS 6.1.3. The progress bar has now been frozen at about two thirds pr