How to get the first or last row value from a group using ntile

I want to query and use ntile to divide by data in 4 groups (quartiles). I got this part no problem and it returns the list of rows and the ntile bucket value for each one.
What I want though is to get only the first row from each ntile group (so in effect the max, q3, median, q1 and min values from the whole result). Of course I coud get max, min and median directly using the other functions, but how about the values for q3 and q1?
My query contains this:
NTILE(4) OVER (ORDER BY salary DESC NULLS LAST) as ntile
So I want the highest, lowest, middle, q3 and q1 values for the salaries.
Should I be using NTILE, ROWNUM, PERCENTIL_DIST....?
Any ideas? Thanks in advance.

SQL> select ename,sal,
  2  NTILE(4) OVER (ORDER BY sal DESC NULLS LAST) as ntile
  3  from emp
  4  /
ENAME             SAL      NTILE
KING             5000          1
FORD             3000          1
SCOTT            3000          1
JONES            2975          1
BLAKE            2850          2
CLARK            2450          2
ALLEN            1600          2
TURNER           1500          2
MILLER           1300          3
WARD             1250          3
MARTIN           1250          3
ENAME             SAL      NTILE
ADAMS            1100          4
JAMES             950          4
SMITH             800          4
14 rows selected.
SQL> select  ename,
  2          sal
  3    from  (
  4           select  ename,
  5                   sal,
  6                   ROW_NUMBER() OVER (PARTITION BY ntile ORDER BY sal DESC NULLS LAST) as rn
  7             from  (
  8                    select  ename,
  9                            sal,
10                            NTILE(4) OVER (ORDER BY sal DESC NULLS LAST) as ntile
11                      from  emp
12                   )
13          )
14    where rn = 1
15  /
ENAME             SAL
KING             5000
BLAKE            2850
MILLER           1300
ADAMS            1100
SQL> SY.

Similar Messages

  • How to get the first and last record

    Hai All
    I have table called T1 and there are more than 8 lakhs records and i have a column called Timestamp so i need to get the first record value and time stampvalue and last record and time stamp value so that i can conclude that For Example
    form 13 june to 15 june data are here
    Kind Regards
    SrikkanthM

    Something like this can also indicate the first and last rows as you query...
    SQL> select empno, ename, hiredate
      2        ,case row_number() over (order by hiredate)
      3           when 1 then 'First Row'
      4           when count(*) over () then 'Last Row'
      5         end as flag
      6  from emp;
         EMPNO ENAME      HIREDATE            FLAG
          7369 SMITH      17/12/1980 00:00:00 First Row
          7499 ALLEN      20/02/1981 00:00:00
          7521 WARD       22/02/1981 00:00:00
          7566 JONES      02/04/1981 00:00:00
          7698 BLAKE      01/05/1981 00:00:00
          7782 CLARK      09/06/1981 00:00:00
          7844 TURNER     08/09/1981 00:00:00
          7654 MARTIN     28/09/1981 00:00:00
          7839 KING       17/11/1981 00:00:00
          7900 JAMES      03/12/1981 00:00:00
          7902 FORD       03/12/1981 00:00:00
          7934 MILLER     23/01/1982 00:00:00
          7788 SCOTT      19/04/1987 00:00:00
          7876 ADAMS      23/05/1987 00:00:00 Last Row
    14 rows selected.
    SQL>

  • How to get the same period last year value using Fiscal Calendar?

    Hi there,
    I am using DAX in a Tabular Model project but I am getting stuck trying to get the following:
    We are using a Fiscal Calendar (from 01 April to 31 March). 
    Previous Period Value
           Value
    2012
    April
    15
    May
    10
    Jun
    20
    2013
    April
    15
    30
    May
    10
    20
    Jun
    20
    25
    I have tried to use sameperiodlastyear but there is an error saying that this function cannot be used for non contiguous dates. DATEADD is given the same error...
    Could anyone help me getting the right measure expressions for [Previous Period Value]?
    Thanks and best regards,
    Joss

    Hi Joss,
    In SQL Server Analysis Services, we can can compare revenue with the hierarchy periods (year, month, day) by using the PARALLELPERIOD function, and now you want to compare with custom periods. (NOTE: We cannot compare it with the PARALLELPERIOD function
    since
    PARALLELPERIOD function returns a member from a prior period in the same relative position as a specified member. So if the first time span not equal to the second one (such as the first period is 3 days, and the second period is 2 month)).  Here
    is a sample query about PARALLELPERIOD function for your reference.
    with
    set Hotels as
    [Hotels].[Hotel ID].&[1015],
    [Hotels].[Hotel ID].&[5640],
    [Hotels].[Hotel ID].&[8800]
    set Period as [Arrival Date].[Date].[Month].&[2012]&[1]:[Arrival Date].[Date].[Month].&[2012]&[12]
    member [Arrival Date].[Date].[0] as sum({ Period })
    member [Total Amount N-1] as (PARALLELPERIOD([Arrival Date].[Date].[Year], 1, [Arrival Date].[Date].[Year].&[2012]), [Measures].[Total Amount])
    select
    [Measures].[Total Amount],
    [Measures].[Total Amount N-1]
    } on 0,
    nonemptycrossjoin
    Hotels,
    Hotels.[Hotel].children,
    *{[Arrival Date].[Date].[0]}
    } on 1
    from [Booking_Cube]
    Regards,
    Charlie Liao
    TechNet Community Support

  • How to get the output of a single command from multiple servers using power shell

    Hi All,
    I have a requirement in my project, wherein I have to find the database list on each server which has autoshrink option is enabled.
    Below is the query which I'm using and I want to automate it in such a way that, I can give the input to powershell script with list of all servers and I need output in csv format which should be giving the database names for which autoshrink option is enabled.
    select name from sys.databases where
    is_auto_shrink_on=1
    Thanks in Advance, Kranthi

    foreach($instance in $instances){
        Invoke-SqlCmd $query -ServerInstance $instance
    https://msdn.microsoft.com/en-us/library/cc281720.aspx
    ¯\_(ツ)_/¯

  • How to get the first day in the month from a domain date ?

    Hi,
    I like to know how to get the first day in the month from a domain date?
    Thanks
    Stephen

    Hi Gokul...
    Instead of using the funtion module you can just write the 3 statements of code to get the first day of the week.
    Its similar to the above one but instead of writing case statement you can achive the following.
    data : w_res type i,
             w_data type d,
    w_res = w_date mod 7.
    w_date = w_date - w_res.
    write w_date.
    This works.
    Regards,
    Siddarth

  • How  to  get the FIRST DAY OF THE CURRENT MONTH

    how to get the FIRST DAY OF THE CURRENT MONTH in oracle 9i.
    plzzzzz send immedaily.advance thanks

    TEST@test SQL> select trunc(sysdate,'MON') from dual;
    TRUNC(SYS
    01-OCT-06
    TEST@test SQL>                                  

  • Apple Mail - how to get the first word in a sentence to auto-capitalize

    How to get the first word in a sentence to auto-capitalize
    Anwar

    something to look forward to then, because we get used not to use our shift button any more, since iPhone and iPad do it for us. entourage and other ms stuff do it. pages does it too now (put it on in the auto-correct in preferences). bizarre however some loose the capitalization when you copy the text. pages to stickies or mail does not. that's good !

  • How to get the first 4 chars form a var ?

    Hi guys,
    How to get the first 4 chars form a var ?
    i.e  temp type num20 value '00000000000012345678'.
    how to move the first 4 chars to another var?
    thx in advance.

    hi
    use OFFESTS..
    example:
    var1 = '12345678'.
    var2 = var1+0(4).
    now var2 conatins '1234'.
    thx
    pavan

  • How to get the form reference in .js page from .jsp page

    hi
    i have written one form in jsp page omething like:-
    <html:form action="/shopping" onsubmit="return false;">
    can anybody tell me,how to get the form reference in .js page from .jsp page ,
    i have tried:-
    var formRef = document.forms[0];
    butits not working.
    Thanks.

    Its very simple......y cant u prefer google...Bad
    c this example...
    function submit()
    alert("textbox"+ document.forms[0].name.value);//to get textbox value in js
    document.forms[0].submit();//to submit jsp page using js
    <html:html>
    <html:form action="/shopping" onsubmit="submit()">
    <html:text property=name>
    learn to search in google..
    </html:form>
    </html:html>

  • How to get the absolute path of a file from the local disk given the file n

    how to get the absolute path of a file from the local disk given the file name

    // will look for the file at the current working directory
    // this is wherever you start the Java application (cound be C: and your
    // application is located in C:/myapp, but the working dir is C:/
    File file = new File("README.txt"); 
    if (file != null && file.exists())
        String absolutePath = file.getAbsolutePath();

  • How to find the average of table row values it should display in next row in libwindow/​CVI

    Hi,
    How to find the average of table row values it should display in next row in libwindow/CVI
    Please let me know the solution.

    There isn't a built-in function to perform calculations on thable cells. What you can do is to retrieve thable cells values and calculate the average by yourself.
    To retrieve a bunch of cells in a single instruction you can use GetTableCellRangeVals: prerequisite for this function to work correctly is that cells are all included in a Rect structure (shortly, a rectangle) and are all of the same data type. See the help for the function for some explanations and the link to an example of its usage. In Cell range parameter you can pass VAL_TABLE_ROW_RANGE (row) macro to retrieve an entire row. See here for details.
    Once you have retrieved cell values in an array, you can pass it to Mean function to calculate the average.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • How to get the first and the last record of every month within a time range in sql

    I am trying to get the first record and the last record of each and every month in a given date range using sql. I have a sample code
    where i have just selected everything within the date range now i have to extract the first and the last records of each and every month.
    SELECT PurOrderNum,
    OrderDate
    FROM Purchasing.PurOrder
    WHERE OrderDate >= '2013-02-28'
    AND OrderDate <= '2014-12-29'

    SELECT PurOrderNum,
    OrderDate
    FROM
    SELECT PurOrderNum,
    OrderDate,
    MAX(OrderDate) OVER (PARTITION BY DATEDIFF(mm,0,OrderDate)) AS MaxDate,
    MIN(OrderDate) OVER (PARTITION BY DATEDIFF(mm,0,OrderDate)) AS MinDate
    FROM Purchasing.PurOrder
    WHERE OrderDate >= '2013-02-28'
    AND OrderDate <= '2014-12-29'
    )t
    WHERE OrderDate = MaxDate
    OR OrderDate = MinDate
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How to get the first month of the year inputed by user manually

    Hi Expert,
    Just like the subject, I 'd like to get the first month of the year inputed by user manually, but don't know how to set the variable, please help.
    For example, user execute a query and input the value of variable Year = 2010, and what I want to get is 201001 into another variable, so that I can use this variable to setup another selection.
    Thank you.
    Andy

    Hi Andy,
    1) U will create a user input varaible for year and say it is ZYEAR.
    2)  U will create another variable  for calmonth  which has processing type : customer exit ..single value ...mandatory ....say ZCMONTH.
    This needs to be populated using the year( user inputted )  and calmonth '001'
    This code will fetch the user input value into ZYEAR and append '001' to the user input value and the value
    will be passed to the ZCMONTH varaible...
    Sample Code is....
    When 'ZCMONTH'.
    IF I_STEP = 2.
         READ TABLE I_T_VAR_RANGE WITH KEY VNAM = 'ZYEAR'.
         IF SY_SUBRC = 0.
                    L_S_RANGE-LOW  =  I_T_VAR_RANGE-LOW.
                   L_S_RANGE-LOW+4(3) = '001'.
                  L_S_RANGE-SIGN = 'I'.
                 L_S_RANGE-OPT  = 'EQ'.
                      APPEND L_S_RANGE TO E_T_RANGE.
        ENDIF.
    ENDIF.
    Regards
    vamsi

  • How to show the First and Last name of the user instead of user name

    Gurus,
    We have the full email id of the user as the portal user name. Right now we are using the "Item Attributes - Current User" to show the user name. We don't want to show this anymore. We would like to show the First and Last name of the user on the Portal page. How can i do this. Please post a reply if you have some idea about it.
    Thanks
    Raj
    ---------

    I believe this is possible using the security APIs. See http://portalstudio.oracle.com/pls/ops/docs/FOLDER/COMMUNITY/PDK/PLSQL/DOC/PLDOC_9026/INDEX.HTML and look for person_info (Returns user information, given a user name)
    under wwsec_api
    Suggest posting any follow-up questions to the Security forum - http://forums.oracle.com/forums/forum.jsp?forum=6

  • How to get the first friday of the MARCH and SEPTEMBER month of any year...

    Hello-
    How can we get the first FRIDAY of MARCH and SEPTEMBER month for any given year.
    Any help would be appreciate!
    Thanks,
    Nikhil

    Hi,
    Please use the following function to get first fiday of any month, we have to pass month,year as varchar2 as input to this function and it will return the
    date in char format, we can convert it to date.
    CREATE OR REPLACE FUNCTION find_fri
    (p_month VARCHAR2,
    p_year VARCHAR2)
    RETURN VARCHAR2 AS
    p_friday VARCHAR2(15);
    BEGIN
    SELECT (CASE triM(TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy'),'DAY')) WHEN 'MONDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy')+4 ,'DD-MM-RRRR')
    WHEN 'TUESDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy')+3 ,'DD-MM-RRRR')
    WHEN 'WEDNESDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy')+2 ,'DD-MM-RRRR')
    WHEN 'THURSDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy')+1 ,'DD-MM-RRRR')
                                                                          WHEN 'FRIDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy'),'DD-MM-RRRR')
                                                                          WHEN 'SATURDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy')+6,'DD-MM-RRRR')
    WHEN 'SUNDAY' THEN TO_CHAR(TO_DATE(p_month||'-'||p_year,'mm-yyyy')+5 ,'DD-MM-RRRR')
                                                                          ELSE 'OTHER'
                                                                          END) INTO p_friday FROM dual;
    RETURN p_friday;
    END;

Maybe you are looking for