Using ROW_NUMBER()

Hi,
I already know the following query is working ( will return 1762 rows)
SELECT
A.TNP_TRACK_ID, A.USER_ID, NVL(A.DELETED,0) DELETED, A.CREATE_TIME,
A.DELETE_TIME,B.PRODUCT_CODE, C.LOGIN_NAME
from MISPNA.TNP_TRACKABLE_201210 A,TMP_VRZ_LATEST_SOC B,MISPNA.tn_login C
where A.TNP_TRACK_ID = B.TRACK_ID and A.USER_ID = C.USER_ID and A.DELETED !=1
but after doing this query, I find out there is one duplicate USER_ID entries, I need to keep only one USER_ID with Largest value in TNP_TRACK_ID,so I can use the following
ROW_NUMBER() OVER (PARTITION BY A.USER_ID ORDER BY A.TNP_TRACK_ID DESC) RN ( RN=1?)
how do I put this condition to query? if the query is correct, I will get 1761 rows since I removeone duplicate USRER_ID row
Thanks a bunch
newbie

You can try this:
select ...
from
   select ...
          row_number() ... rn
   from   ...
   where  ...
where rn = 1;

Similar Messages

  • Generating sequence Using row_number function.

    Hello All,
    I want to know if we can create sequence using row_number .
    I know we can create sequence using row_number but I want to start my sequence from 001, can we create using row_number?
    It will be great, If I can get a faster response.
    Thanks in advance.

    user13034857 wrote:
    Hello All,
    I want to know if we can create sequence using row_number .
    I know we can create sequence using row_number but I want to start my sequence from 001, can we create using row_number?
    It will be great, If I can get a faster response.
    Thanks in advance.
    SQL> set pagesize 60
    SQL> SELECT   TO_CHAR (ROWNUM, '000') Seq, s.table_name
      2    FROM   user_tables s
      3   WHERE   ROWNUM <= 20;
    SEQ  TABLE_NAME
    001 ICOL$
    002 CON$
    003 UNDO$
    004 PROXY_ROLE_DATA$
    005 FILE$
    006 UET$
    007 IND$
    008 SEG$
    009 COL$
    010 CLU$
    011 PROXY_DATA$
    012 TS$
    013 BOOTSTRAP$
    014 FET$
    015 CCOL$
    016 USER$
    017 OBJ$
    018 TAB$
    019 CDEF$
    020 OBJERROR$
    20 rows selected.
    SQL>
    SQL> SELECT   TO_CHAR (ROW_NUMBER () OVER ( ORDER BY dept),
      2                    '000')
      3              Seq,
      4           empno,
      5           ename,
      6           dept
      7    FROM   Emp;
    SEQ       EMPNO ENAME                                DEPT
    001       2345 zxcv                                   10
    002       1111 qwer                                   10
    003       1234 asdf                                   20
    004       5657 ghjk                                   20
    005       3125 tyui                                   30
    006       2134 zxvnb                                  30
    007       8907 cvmn                                   30
    7 rows selected.
    SQL>
    SQL>

  • Can we Filter the records using ROW_NUMBER() funtion?

    Oracle 10G
    Hi all,
    In the below query i used ROW_NUMBER() function to get the rownum value after descending order the results.
    How Can i filter the first 10 rows without using a subquery?
    I tried to use alias names but it doesn't work. Is there a way or it should be done only with subqueries?
    select article_type_id,
    article_type_desc,
    ROW_NUMBER() OVER ( order by article_type_id desc) rnum
    from s_article_types
    Results are
    ARTICLE_TYPE_ID     ARTICLE_TYPE_DESC     RNUM
    37     Non-Degree News     1
    36     Career News     2
    35     ET News     3
    34     Hotcourses 2.0 General     4
    33     Hotcourses 2.0 Permanent     5
    32     Hotcourses 2.0 News     6
    1 General news 37
    Thanks in advance

    You can do
    select * from
      select article_type_id, 
      article_type_desc,
      ROW_NUMBER() OVER ( order by article_type_id desc) rnum
      from s_article_types
    where rnum <= 10You can't do it direct.

  • Can I rewrite the following query without using Row_number() function ??!!

    Hello every one, can I rewrite the following query without using the 'ROW_NUMBER() OVER ' part.
    The query is supposed to pull out the records whose CODE is not NULL and has most
    recent date for UPDATE_DATE . The reason I wanted to do this is, When I embed this query
    in between many other queries along with JOINs, My oracle server is unable to execute. So, I thought
    its better to supplant 'ROW_NUMBER() OVER ' logic with something else and try it. .
    SELECT a.* FROM
    (SELECT b.*, ROW_NUMBER() OVER (PARTITION BY b.PIDM
    ORDER BY b.UPDATE_DATE DESC) AS Rno
    FROM
    SELECT *
    FROM SHYNCRO WHERE CODE IS NOT NULL
    )b
    )a
    WHERE a.Rno = 1

    Hi,
    You didn't write over 150 lines of code and then start testing it, did you?
    Don't.
    Take baby steps. Write as little as pssiblem test that. Debug and test again until you have something that does exactly what you want it to do.
    When you have somehting that works perfectly, take one baby step. Add a tiny amount of code, maybe 1 or 2 lines more, and test again.
    When you do get an error, or wrong results, you'll have a much better idea of where the problem is. also, you won't be building code on a flimsy foundation.
    If you need help, post the last working version and the new version with the error. Explain what you're trying to do in the new version.
    The error message indicates line 133. It looks like line 133 of your code is blank. Does your front end allow completely blank lines in the middle of a query? SQL*Plus doesn't by default; you have to say
    SET  SQLBLANKLINES  ONto have a completely blank line in SQL*Plus. (However, lines containing nothing but at commnet are always allowed.)
    You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (such as indented code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    The 4 people who posted small code fragments for you to read all did this.  It would be so much easier for people to read your humongeous query if it were formatted.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How can use row_number() over partition by plz provide some doc.

    row_number() over (partition by)
    what is this and how can use it in sql query.
    if ur have any documentation of it. plz give...me..
    thanx sir
    thanx in advance.

    http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/functions105a.htm
    SELECT empno, deptno,
    row_number() over (partition by deptno order by empno) rn
    from scott.emp
         EMPNO     DEPTNO RN                                    
          7782             10     1
          7839             10     2
          7934             10     3
          7369             20     1
          7566             20     2
          7788             20     3
          7876             20     4
          7902             20     5
          7499             30     1
          7521             30     2
          7654             30     3
          7698             30     4
          7844             30     5
          7900             30     6Regards
    Dmytro

  • Use ROW_NUMBER as a join to in a query.

    Hello
    I have created the following code from assistance on a previous post which works great
    ;WITH C AS
    SELECT
    ROW_NUMBER() OVER(PARTITION BY Introducer
    ORDER BY Introducer) AS rownum, Introducer, BDM, TargetDate
    FROM Reporting.dbo.IntroducerDailyReferrals
    WHERE TargetDate = '2014-09-01'
    SELECT rownum, Introducer, BDM, Targetdate
    FROM C
    How do I Insert the above query as a part of a join instead of a table link?
    Thanks

    Sub query?
    SELECT * FROM tb1 JOIN (
    SELECT
    ROW_NUMBER() OVER(PARTITION BY Introducer
    ORDER BY Introducer) AS rownum, Introducer, BDM, TargetDate
    FROM Reporting.dbo.IntroducerDailyReferrals
    WHERE TargetDate = '2014-09-01'
    ) AS DER ON tbl.PK=DER.something
    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

  • WITHOUT USING ROW_NUMBER FUNCTIONS IN T-SQL

    INPUT:-
    CUST_ID
    GIFT_ID
    100
    10
    100
    20
    100
    30
    200
    10
    200
    20
    200
    30
    300
    20
    OUTPUT:-
    CUST_ID
    GIFT_ID
    SEQ
    100
    10
    1
    100
    20
    2
    100
    30
    3
    200
    10
    1
    200
    20
    2
    200
    30
    3
    300
    20
    1
    santoshbangalore

    THANK YOU SO MUCH FOR YOUR ANS? BUT MY INPUT TABLE A CONTAIN ONLY TWO COLUMN'S 
    CUST_ID,GIFT_ID
    AND IN OUT PUT I NEED THE ABOVE OUTPUT WITH 
    CUST_ID,GIFT_ID,ROW_NUMBER AS SHOWN ABOVE?
    santoshbangalore

  • Not right data when row_number used in inner-view sql query...

    Hi ,
    I use the below sql statement which displays the right data
    select CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE , SUM_POSOTITA , row_number() over(partition by code_farmakou order by sum_posotita desc) from
      (SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES ,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_AT_SINT_CLINIC A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_AT_SINT_EX_IATR A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_AT_SINT_FOREON_MS A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_GEN_SINT_KLIN A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_GEN_SINT_EX_IATR A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS)The data are:
    CODE_FARMAKOU                            EMP_NAME                                                                         PACKTYPE                     PACKSIZE                  SUM_POSOTITA ROW_NUMBER()OVER(PARTITIONBYCO
    0000002419                               FACTREL INJECTION                                                                VIAL                         2 ML                                 5                              1
    0000014071                               DOPAMINE HYDROCHLORIDE                                                           VIAL                         5 ML X 25                           30                              1
    0000086289                               DETUSSIN EXPECTORANT                                                             BOT                          120 ML                               3                              1
    1000000760                               DEPON                                                                            BT                           20(BLIST2X10)                        2                              1
    1000000760                               DEPON                                                                            BT                           20(BLIST2X10)                        1                              2
    1000003279                               MOXACEF                                                                          BT                           40(BLIST10X4)                       45                              1
    1000003279                               MOXACEF                                                                          BT                           40(BLIST10X4)                        1                              2
    1000003279                               MOXACEF                                                                          BT                           40(BLIST10X4)                        1                              3
    1000014127                               DEPON VIT. C                                                                     BT                           2TUBX10                              6                              1
    1000014127                               DEPON VIT. C                                                                     BT                           2TUBX10                              2                              2
    1000016655                               KABIVEN                                                                          BT                           50ÖÕÓ.×1,7ML                        21                              1
    1000016655                               KABIVEN                                                                          BT                           50ÖÕÓ.×1,7ML                         2                              2However , when i use the below statement , in order not to display the row_number (so i use row_number function in inner-view) the data are different--in different order... why is that????
    select CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE , SUM_POSOTITA from
    select CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE , SUM_POSOTITA , row_number() over(partition by code_farmakou order by sum_posotita desc) from
      (SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES ,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_AT_SINT_CLINIC A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_AT_SINT_EX_IATR A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_AT_SINT_FOREON_MS A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_GEN_SINT_KLIN A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS
      UNION ALL
      SELECT CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, TO_DATE(DATES_EKTELESIS,'DD/MM/RRRR') DATES,SUM(POSOTITA) SUM_POSOTITA
              FROM  EKTELESI_GEN_SINT_EX_IATR A, MITROO_FARMAKOU B
               WHERE CODE_FARMAKOU = FARMAK_CODE
               GROUP BY CODE_FARMAKOU,EMP_NAME,PACKTYPE,PACKSIZE, DATES_EKTELESIS)
      )and its data are:
    CODE_FARMAKOU                            EMP_NAME                                                                         PACKTYPE                     PACKSIZE                  SUM_POSOTITA
    1000016655                               KABIVEN                                                                          BT                           50ΦΥΣ.Χ1,7ML                        21
    1000016655                               KABIVEN                                                                          BT                           50ΦΥΣ.Χ1,7ML                         2
    1000000760                               DEPON                                                                            BT                           20(BLIST2X10)                        2
    1000014127                               DEPON VIT. C                                                                     BT                           2TUBX10                              2
    1000003279                               MOXACEF                                                                          BT                           40(BLIST10X4)                       45
    0000014071                               DOPAMINE HYDROCHLORIDE                                                           VIAL                         5 ML X 25                           30
    0000086289                               DETUSSIN EXPECTORANT                                                             BOT                          120 ML                               3
    1000014127                               DEPON VIT. C                                                                     BT                           2TUBX10                              6
    1000003279                               MOXACEF                                                                          BT                           40(BLIST10X4)                        1
    1000003279                               MOXACEF                                                                          BT                           40(BLIST10X4)                        1
    0000002419                               FACTREL INJECTION                                                                VIAL                         2 ML                                 5
    1000000760                               DEPON                                                                            BT                           20(BLIST2X10)                        1NOTE :Sorry, I tried to pose some sample data using the "with" statement but i couldn't...the error ORA-32035 : unreferenced query name defined in WITH clause was displayed..
    Regards,
    Simon

    The optimizer has, well, optimized out the row_number because you never refer to its value in the outermost query.
    sql>select deptno, cnt, row_number() over (order by cnt desc) rn
      2    from (select deptno, count(*) cnt
      3            from emp
      4           group by deptno);
       DEPTNO       CNT        RN
           30         6         1
           20         5         2
           10         3         3
    3 rows selected.
    -- here because we include rn in the outermost query,
    -- the results are still ordered based on the analytical function result
    sql>select deptno, cnt, rn
      2    from (select deptno, cnt, row_number() over (order by cnt desc) rn
      3            from (select deptno, count(*) cnt
      4                    from emp
      5                   group by deptno));
       DEPTNO       CNT        RN
           30         6         1
           20         5         2
           10         3         3
    3 rows selected.
    -- but if we don't include rn in the outermost query,
    -- the optimizer leaves out the window sort and the results are in a different order
    sql>select deptno, cnt
      2    from (select deptno, cnt, row_number() over (order by cnt desc) rn
      3            from (select deptno, count(*) cnt
      4                    from emp
      5                   group by deptno));
       DEPTNO       CNT
           10         3
           20         5
           30         6
    3 rows selected.This just reinforces the point that if you want your results in a particular order, you need to provide an ORDER BY clause - don't rely on execution plans to do your sorting for you.

  • Error while using row_num function in forms6i

    Oracle forms6i
    Hai
    While using row num function in my forms i had a error.
    My coding is
    declare
    pin_no varchar2(16);
    pin_date date;
    pin_time varchar2(25);
    mstr varchar2(200);
    m_file TEXT_IO.FILE_TYPE;
    m_file_path varchar2(100) := :global.filename;
    line_count number;
    M_BARCODE VARCHAR2(16);
    M_BARDATE DATE;
    M_BARTIME varchar2(25);
    M_No number;
    Cursor c1 is
    select barcode,bardate,bartime,
    row_number() over (partition barcode order by bartime) as RN-------------------the error at this line
    from temp_attendance
    group by barcode,bardate,bartime
    order by bardate;
    begin
    If m_file_path is not null then
    m_file:= TEXT_IO.fopen(m_file_path, 'r');
    --DELETE FROM temp_attendance;     
    Loop
    begin
    TEXT_IO.get_line(m_file,mstr);
    mstr := ltrim(rtrim(mstr));
    M_barcode :=substr(mstr,1,16);
    M_bardate := to_date(substr(mstr,17,8),'DD/MM/YYYY');
    M_bartime := (substr(mstr,25,4));
    INSERT INTO temp_attendance(BARCODE,BARDATE,BARTIME,RN) VALUES(M_BARCODE,M_BARDATE,M_BARTIME,M_No);
    Exception
    when no_data_found then
    text_io.fclose(m_file);
    exit;
    End;
    End loop;
    go_block('TEST_MS1');
    clear_block(no_validate);
    For r1 in c1 loop
         :barcode := r1.barcode;
         :bardate := r1.bardate;
         :bartime := r1.bartime;
         next_Record;
    end loop;
    first_record;
    end if;
    exception
    when others then
    forms_ddl('ROLLBACK');
    message (sqlerrm);
    end;
    Thanks & Regards
    Srikkanth.M

    Hi,
    Try using:
    row_number() over (partition BY barcode order by bartime) as RN
    If that wasn't the problem, what is the error you are getting?
    Regards.

  • Storing XML using XSU, object VIEW and INSTEAD OF trigger

    Here is the point:
    I've got 2 tables which are linked:
    CREATE TABLE dept (
    deptno NUMBER PRIMARY KEY,
    deptname VARCHAR2(20)
    CREATE TABLE emp (
    empno NUMBER PRIMARY KEY,
    empname VARCHAR2(20),
    deptno NUMBER REFERENCES dept(deptno)
    I've got the following message, which I want to insert in the tables using XSU (I already have a PL/SQL stored procedure which work perfectly for insertion into 1 table, using DBMS_XMLSave.insertXML or xmlgen.insertXML):
    <DEPT>
    <DEPTNO>10</DEPTNO>
    <DEPTNAME>IT</DEPTNAME>
    <EMP>
         <EMPNO>1</EMPNO>
         <EMPNAME>John</EMPNAME>
    </EMP>
    <EMP>
         <EMPNO>1</EMPNO>
         <EMPNAME>Phil</EMPNAME>
    </EMP>
    </DEPT>
    So I've created the following object:
    CREATE TYPE emp_t AS OBJECT
    empno NUMBER,
    empname VARCHAR2(20)
    CREATE TYPE emplist_t AS TABLE OF emp_t;
    CREATE TYPE dept_t AS OBJECT
    deptno NUMBER,
    deptname VARCHAR2(20),
    emplist emplist_t
    Now I understand that I should create an object VIEW and an INSTEAD OF trigger (That's what I read many times),
    but I don't know how to structure the view and the trigger.
    Could you help? (Example of a similar context, piece of code)
    Thanks a lot
    Marion

    Hi John,
    I have exactly the same issue as you experienced back in January. I have a complex data modelling requirement which requires the need to pivot rows into columns using ROW_NUMBER() and PARTITION clauses. To hide the complexity from the middle tier, I have created a database view and appropriate INSTEAD OF triggers and mapped my EO to the view. I have overriden the lock() method on the EO implementation class (to avoid ORA-02014) and would like to try the same solution you used with the pl/sql call to lock the record.
    My question is, how did you manage the release of the lock if the transaction was not rolled back or committed by your application i.e. if the user closed the browser for instance.
    In my naivity, I would like to think that the BC4J framework would release any locks for the database session when it found the servlet session to be terminated however my concern is that the lock would persist and cause complications.
    Any assistance greatly appreciated (if you would be willing to supply your lock() method and pl/sql procedure logic I would be even more grateful!).
    Many thanks,
    Dave
    London

  • Need a maximum date value using group by

    Create table student (dept number(10), dep_name varchar2(10),join_date date,years_attended number(10),end_date date);
    insert into student values (1,'I',to_date('3/7/1917','MM/DD/YYYY'),4,to_date('8/26/1987','MM/DD/YYYY'));
    insert into student values (1,'I',to_date('1/1/1900','MM/DD/YYYY'),4,to_date('8/26/1932','MM/DD/YYYY'));
    insert into student values (1,'D',to_date('1/1/1920','MM/DD/YYYY'),5,to_date('8/26/1994','MM/DD/YYYY'));
    insert into student values (1,'C',to_date('1/1/1920','MM/DD/YYYY'),6,to_date('8/26/1945','MM/DD/YYYY'));
    insert into student values (2,'I',to_date('7/1/1900','MM/DD/YYYY'),3,to_date('8/26/1932','MM/DD/YYYY'));
    insert into student values (2,'I',to_date('8/16/1916','MM/DD/YYYY'),9,to_date('8/26/1923','MM/DD/YYYY'));
    insert into student values (2,'D',to_date('8/16/1916','MM/DD/YYYY'),10,to_date('8/26/1987','MM/DD/YYYY'));
    insert into student values (3,'I',to_date('3/7/1917','MM/DD/YYYY'),4,to_date('8/26/1987','MM/DD/YYYY'));
    insert into student values (3,'D',to_date('7/28/1920','MM/DD/YYYY'),6,to_date('8/26/1945','MM/DD/YYYY'));
    insert into student values (3,'I',to_date('7/28/1920','MM/DD/YYYY'),8,to_date('8/26/1965','MM/DD/YYYY'));
    insert into student values (4,'I',to_date('12/31/1924','MM/DD/YYYY'),2,to_date('8/26/1998','MM/DD/YYYY'));
    insert into student values (4,'I',to_date('6/10/1929','MM/DD/YYYY'),1,to_date('8/26/1943','MM/DD/YYYY'));
    insert into student values (4,'C',to_date('1/17/1927','MM/DD/YYYY'),4,to_date('8/26/1955','MM/DD/YYYY'));
    insert into student values (4,'C',to_date('6/10/1929','MM/DD/YYYY'),30,to_date('8/26/1967','MM/DD/YYYY'));
    insert into student values (5,'D',to_date('2/10/1931','MM/DD/YYYY'),2,to_date('8/26/1943','MM/DD/YYYY'));
    insert into student values (5,'I',to_date('2/10/1931','MM/DD/YYYY'),24,to_date('8/26/1962','MM/DD/YYYY'));
    commit;I need a maximum date value join_date for each department. If max(join_date) has two records for each dept then max(end_date) should be considered. I have used a below select query
    select * from student where join_date in (select
    max(join_date) from student group by dept);which gives me the following result
    1     D     1/1/1920     5     8/26/1994
    1     C     1/1/1920     6     8/26/1945
    2     I     8/16/1916     9     8/26/1923
    2     D     8/16/1916     10     8/26/1987
    3     D     7/28/1920     6     8/26/1945
    3     I     7/28/1920     8     8/26/1965
    4     I     6/10/1929     1     8/26/1943
    4     C     6/10/1929     30     8/26/1967
    5     D     2/10/1931     2     8/26/1943
    5     I     2/10/1931     24     8/26/1962But I am looking for the result which gives me only one maximum value for each dept column. First it should look for maximum value of join_date, if two records has same join_date then max(end_date) should be considered. The result should be sumthing like this
    1     D     1/1/1920     5     8/26/1994
    2     D     8/16/1916     10     8/26/1987
    3     I     7/28/1920     8     8/26/1965
    4     C     6/10/1929     30     8/26/1967
    5     I     2/10/1931     24     8/26/1962Can you please tell me how to rewrite the select query to get the above results.
    Edited by: user11872870 on Aug 2, 2011 5:29 PM
    Edited by: user11872870 on Aug 2, 2011 5:36 PM

    Hi,
    That's called a Top-N Query , and here's one way to do it:
    WITH     got_r_num     AS
         SELECT     student.*
         ,     ROW_NUMBER () OVER ( PARTITION BY  dept
                                   ORDER BY          join_date     DESC
                             ,                end_date     DESC
                           )      AS r_num
         FROM    student
    SELECT       dept, dep_name, join_date, years_attended, end_date
    FROM       got_r_num
    WHERE       r_num     = 1
    ORDER BY  dept
    ;Another way is similar to what you originally posted:
    SELECT    *
    FROM       student
    WHERE        (dept, join_date, end_date)
                   IN (
                        SELECT    dept
                   ,       MAX (join_date)
                   ,       MAX (end_date) KEEP (DENSE_RANK LAST ORDER BY join_date)
                   FROM      student
                   GROUP BY     dept
                   );I suspect the first way (using ROW_NUMBER) will be faster.
    Also, the ROW_NUMBER approach is guaranteed to return only 1 row per dept. Using the GROUP BY approach,if there is a tie on join_date and end_date, then it will return all contenders in that dept. Using ROW_NUMBER, it's easy to add as many tie-breaking expressions as you want, and, if there is still a tie, it will arbirarily pick one of the rows involved in the tie as #1.
    Thanks for posting the CREATE TABLE and INSERT statments! That's very helpful.
    Edited by: Frank Kulash on Aug 2, 2011 9:00 PM
    Added GROUP BY alternative

  • How to achive this using analytical function-- please help

    version 10g.
    this code works just fine with my requirement. i am tyring to learn analytical functions and implement that in the below query. i tried using row_number ,
    but i could nt achive the desired results. please give me some ideas.
    SELECT c.tax_idntfctn_nmbr irs_number, c.legal_name irs_name,
           f.prvdr_lctn_iid
      FROM tax_entity_detail c,
           provider_detail e,
           provider_location f,
           provider_location_detail pld
    WHERE c.tax_entity_sid = e.tax_entity_sid
       AND e.prvdr_sid = f.prvdr_sid
       AND pld.prvdr_lctn_iid = f.prvdr_lctn_iid
       AND c.oprtnl_flag = 'A'
       AND c.status_cid = 2
       AND e.oprtnl_flag = 'A'
       AND e.status_cid = 2
       AND (c.from_date) =
              (SELECT MAX (c1.from_date)
                 FROM tax_entity_detail c1
                WHERE c1.tax_entity_sid = c.tax_entity_sid
                  AND c1.oprtnl_flag = 'A'
                  AND c1.status_cid = 2)
       AND (e.from_date) =
              (SELECT MAX (c1.from_date)
                 FROM provider_detail c1
                WHERE c1.prvdr_sid = e.prvdr_sid
                  AND c1.oprtnl_flag = 'A'
                  AND c1.status_cid = 2)
       AND pld.oprtnl_flag = 'A'
       AND pld.status_cid = 2
       AND (pld.from_date) =
              (SELECT MAX (a1.from_date)
                 FROM provider_location_detail a1
                WHERE a1.prvdr_lctn_iid = pld.prvdr_lctn_iid
                  AND a1.oprtnl_flag = 'A'
                  AND a1.status_cid = 2)thanks
    Edited by: new learner on May 24, 2010 7:53 AM
    Edited by: new learner on May 24, 2010 10:50 AM

    May be like this not tested...
    select *
    from
    SELECT c.tax_idntfctn_nmbr irs_number, c.legal_name irs_name,
    f.prvdr_lctn_iid, c.from_date as c_from_date, max(c.from_date) over(partition by c.tax_entity_sid) as max_c_from_date,
    e.from_date as e_from_date, max(e.from_date) over(partition by e.prvdr_sid) as max_e_from_date,
    pld.from_date as pld_from_date, max(pld.from_date) over(partition by pld.prvdr_lctn_iid) as max_pld_from_date
    FROM tax_entity_detail c,
    provider_detail e,
    provider_location f,
    provider_location_detail pld
    WHERE c.tax_entity_sid = e.tax_entity_sid
    AND e.prvdr_sid = f.prvdr_sid
    AND pld.prvdr_lctn_iid = f.prvdr_lctn_iid
    AND c.oprtnl_flag = 'A'
    AND c.status_cid = 2
    AND e.oprtnl_flag = 'A'
    AND e.status_cid = 2
    AND pld.oprtnl_flag = 'A'
    AND pld.status_cid = 2
    )X
    where c_from_date=max_c_from_date AND e_from_date =max_e_from_date AND
    pld_from_date=max_pld_from_date

  • Issue with ROW_NUMBER() OVER (PARTITION)

    Hi,
    Please read the Thread completely, I have created a Report to see Yearly Turnover%, The report works fine but when I take Quarter and Months in it, it restricts the result to only 1 line(i.e., my first year's Turnover) and when I opened the Physical query, I saw the BI Server is using
    ROW_NUMBER() OVER (PARTITION BY)
    which is not at all necessary.
    *I tried disabling WITH_CLAUSE_SUPPORTED and PERF_PREFER_MINIMAL_WITH_USAGE but didn't get any resolution, Could anybody help me out?
    thanks in Advance,
    Anand

    You said 'it restricts the result to only 1 line' means the value is nor drill down to next level?
    In that case Yearly Turnover% is set to Year level?

  • Max sal using set or join operations

    Hi,
    how to write a sql query to retrieve max sal of an emp table without using max()function.
    and using only set operations or join conditions..
    cheers..

    You can use an analytic function for this. You can either use ROW_NUMBER or RANK or DENSE_RANK
    with my_emp
    as
    select empno, ename, sal, rank() over(order by sal desc) rk
      from emp
    select empno, ename, sal
      from my_emp
    where rk = 1

  • Row_number()  with distinct

    How to use row_number() with distinct ?
    I want all the selected in distinct display but it only can display (a) table. How can i add more table in select row_number() ??
    Here is my query.
    SELECT
    ROW_NUMBER() OVER (ORDER BY a.student_number) as No
    FROM
    SELECT DISTINCT
    TO_CHAR(TO_DATE(c.study_intake, 'yyyymm'), upper('mon yyyy')) AS Study_intake,
         a.student_number,
         a.name,
         b.course_code,
         b.academic_semester,
         e.qualification,
         e.school,
         e.state,
         f.school_town,
         a.permanent_tel_no,
         a.mobile_no
    FROM
         student_data a,
         student_course_master b,
         student_course_detail_subject c,
         student_qualification e,
         school_master f
    WHERE
         a.student_number = b.student_number
    AND b.student_key = c.student_key
    AND e.student_key = a.student_key
    AND b.student_course_status IN ('Completed','Active')
    AND e.school = f.school_name(+)
    AND e.state = f.state(+)      
    )a

    Did not get any help from them ;)
    Regards,
    Guru

Maybe you are looking for

  • WHY CAN'T I ACCESS THE TRASH SECTION OF MY BACKUP ASSISTANT??

    IT'LL SHOW NOTHING WHEN I CLICK ON IT EVEN THOUGH I HAVE DELETED CONTACTS THEN USED BACKUP ASSISTANT ON MY PHONE BUT NOT DELETED THEM PPERMANENTLY ON THE WEB SITE

  • How to batch change Caption with version name?

    I'm using Aperture 3.0.2. I want to caption the photos based on version name. This way when I export the photos from Aperture to Picasaweb, the caption will show. This will allow the visitors to tell me which image proof that I need to re-touch.

  • How to use simple abap program O/P using bsp.

    Hi All, I want to know simple BSP program which will call normal abap program. It has to display simple output not in table format. Thanks,

  • Automatic Error when opening Disk Utility

    Hi guys, I recently noticed this problem when clicking "Calculate Image Checksum..." in the finder pulldown menu for Disk Utility. I don't open Disk Utility often, so I can't be sure if this error has always existed or if it only has recently began o

  • Set ZATTR_PROD may only be changed in the original system

    Please, Iu2019ve enhancement the PRODUCT_CUSTOMER2 BADI to change product attribute type when Iu2019m replicating products from ECC to CRM. When I try to replicate the material from ECC to CRM thereu2019s the follow error: "Set ZATTR_PROD may only be