Pickup the Latest Result Date (Query involves 3 tables)

Hello folks,
I have a relatively simple request. It involves 3 simple tables. I want to return the Student along with the Results based on the Latest Result Date and a Flag. Any help is appreciated.
Thanks
Assumptions
STUDENT_ID is unique in STUDENT_TB
EXAM_VISIT_ID is Unique in EXAM_RESULTS_TB.
Scripts for table creation and INSERT statements
create table student_tb (student_id varchar2(4));
create table exam_tb (student_id varchar2(4), exam_visit_id number, exam_date date);
create table exam_results (exam_visit_id number, result_date date, results number, result_flag varchar2(1));
insert into student_tb values('1001');
insert into student_tb values('1002');
Insert into EXAM_TB (STUDENT_ID,EXAM_DATE,EXAM_VISIT_ID) values ('1001',to_date('01-JAN-12','DD-MON-RR'),1);
Insert into EXAM_TB (STUDENT_ID,EXAM_DATE,EXAM_VISIT_ID) values ('1001',to_date('01-APR-12','DD-MON-RR'),2);
Insert into EXAM_TB (STUDENT_ID,EXAM_DATE,EXAM_VISIT_ID) values ('1001',to_date('01-JUL-12','DD-MON-RR'),3);
Insert into EXAM_TB (STUDENT_ID,EXAM_DATE,EXAM_VISIT_ID) values ('1001',to_date('01-SEP-12','DD-MON-RR'),4);
Insert into EXAM_RESULTS_TB (EXAM_VISIT_ID,RESULT_DATE,FLAG,RESULTS) values (1,to_date('01-FEB-12','DD-MON-RR'),'N',10);
Insert into EXAM_RESULTS_TB (EXAM_VISIT_ID,RESULT_DATE,FLAG,RESULTS) values (2,to_date('01-MAY-12','DD-MON-RR'),'Y',40);
Insert into EXAM_RESULTS_TB (EXAM_VISIT_ID,RESULT_DATE,FLAG,RESULTS) values (3,to_date('01-AUG-12','DD-MON-RR'),'Y',32);
Insert into EXAM_RESULTS_TB (EXAM_VISIT_ID,RESULT_DATE,FLAG,RESULTS) values (4,to_date('01-DEC-12','DD-MON-RR'),'N',20);I would like to pick up the Student along with the RESULT_DATE and RESULTS where the RESULT_DATE (EXAM_DATE is irrelevant for this exercise) is the most recent for that Student and the flag = 'Y'. EXAM_VISIT_ID is Unique. So, the record that needs to be returned from this Result set is
1001 3 01-AUG-12 32

Hi,
That's an example of a Top-N Query , and here's one way to do it:
WITH   got_r_num   AS
     SELECT  e.student_id, e.exam_visit_id
     ,     er.result_date, er.results
     ,     RANK () OVER ( PARTITION BY  e.student_id
                           ORDER BY          er.result_date  DESC
                    )           AS r_num
     FROM    exam_tb              e
     JOIN     exam_results_tb  er  ON   er.exam_visit_id  = e.exam_visit_id
     WHERE     er.flag     = 'Y'
SELECT  student_id, exam_visit_id
,     result_date, results
FROM     got_r_num
WHERE     r_num     = 1
;Thanks for posting the CREATE TABLE and INSERT statements. Please make sure they work before posting them. There is some confusion about the table (EXAM_RESULTS or EXAM_RESULTS_TB) and column (FLAG or RESULT_FLAG) names.
What results do you want if there is a tie for the most recent exam for a given student? (E.g., if we change the result_date on this row
Insert into EXAM_RESULTS_TB (EXAM_VISIT_ID,RESULT_DATE,FLAG,RESULTS) values (2,to_date('01-MAY-12','DD-MON-RR'),'Y',40);to be August 1, 2012, just like the row with exam_visit_id=3)?
Depending on your requirements, you may want to add tie-breaking columns to the end of the analytic ORDER BY clause, and/or use ROW_NUMBER instead of RANK.

Similar Messages

  • Find the latest updated or the latest inserted record  in a table

    Hi All,
    Thanks in advance
    Just a simple question
    How do we find the latest updated or the latest inserted record in a table ?
    Provide some queries in SQL?

    You can order by rowid desc to get lately inserted records, but I'm not sure about updated records.That is incorrect, Oracle might use old rowid's even in inserts and you cannot assure that the max(rowid) refers to the latest record.
    If the table is created with rowdependencies one can use ORA_ROWSCN pseudo column to check on date/time when the last dml has been performed over that table. But, that has some limitations too, Old snapshots will be erased hence one can check the last dml with a time frame of few days.
    Regards,
    Prazy

  • Find the latest Start date after a gap in date Field For each id

    Hi All, Can anyone help me in this, as it is so urgent ..My requirement is to get the latest start date after a gap in a month for each id and if there is no gap for that particular id minimum date for that id should be taken….Given below the scenario
    ID          StartDate
    1            2014-01-01
    1            2014-02-01
    1            2014-05-01-------After Gap Restarted
    1            2014-06-01
    1            2014-09-01---------After last gap restarted
    1            2014-10-01
    1            2014-11-01
    2            2014-01-01
    2           2014-02-01
    2            2014-03-01
    2            2014-04-01
    2            2014-05-01
    2            2014-06-01
    2            2014-07-01
    For Id 1 the start date after the latest gap is  2014-10-01 and for id=2 there is no gap so i need the minimum date  2014-01-01
    My Expected Output
    id             Startdate
    1             2014-10-01
    2             2014-01-01
    Expecting your help...Thanks in advance

    If you're using SQL Server 2012 this will work for you...
    IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp
    GO
    CREATE TABLE #temp (
    ID INT,
    StartDate DATE
    INSERT #temp (ID, StartDate) VALUES
    (1,'2014-01-01'),
    (1,'2014-02-01'),
    (1,'2014-05-01'),
    (1,'2014-06-01'),
    (1,'2014-09-01'),
    (1,'2014-10-01'),
    (1,'2014-11-01'),
    (2,'2014-01-01'),
    (2,'2014-02-01'),
    (2,'2014-03-01'),
    (2,'2014-04-01'),
    (2,'2014-05-01'),
    (2,'2014-06-01'),
    (2,'2014-07-01')
    -- SQL 2012 and later --
    ;WITH gg AS (
    SELECT
    COALESCE(DATEDIFF(mm, LAG(t.StartDate, 1) OVER (PARTITION BY t.ID ORDER BY t.StartDate), t.StartDate), 2) AS GetGap
    FROM #temp t
    ), did AS (
    SELECT DISTINCT t.ID FROM #Temp t
    SELECT
    did.ID,
    x.StartDate
    FROM
    did
    CROSS APPLY (
    SELECT TOP 1
    gg.StartDate
    FROM gg
    WHERE did.ID = gg.ID
    AND gg.GetGap > 1
    ORDER BY gg.StartDate DESC
    ) x
    If you're on an earlier version than 2012, let me know. It's an easy rewrite but the final code isn't as efficient.
    Jason Long

  • How does the GR processing time affect the scheduling of the process order & the latest start date in the operation.

    Hi
    Can anyone explain  how does the GR processing time affect the scheduling of the process order & the latest start date in the operation overview.

    Hi
    GR processing time means number of workdays required after receiving the material in storage.
    Check this link:GR Processing time
    Regards,
    Anupam Sharma

  • How to store the flat file data into custom table?

    Hi,
    Iam working on inbound interface.Can any one tell me how to store the flat file data into custom table?what is the procedure?
    Regards,
    Sujan

    Hie
    u can use function
    F4_FILENAME
    to pick the file from front-end or location.
    then use function
    WS_UPLOAD
    to upload into
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'   "Function to pick file
        EXPORTING
          field_name = 'p_file'     "file
        IMPORTING
          file_name  = p_file.     "file
      CALL FUNCTION 'WS_UPLOAD'
       EXPORTING
         filename                       = p_file1
        TABLES
          data_tab                      = it_line
    *then loop at it_line splitting it into the fields of your custom table.
    loop at it_line.
              split itline at ',' into
              itab-name
              itab-surname.
    endloop.
    then u can insert the values into yo table from the itab work area.
    regards
    Isaac Prince

  • How to find the structure fields data in database tables?

    how to find the structure fields data in database tables?

    Your question doesn't appear to be Web Dynpro ABAP related. Please only post questions in this forum if they are directly Web Dynpro ABAP related.  There are several other more general ABAP related forums.

  • HT1600 Since the latest up-date I can't see any movies.  I always returns to the main menu.  Is anyone else having this problem and how do I fix it?

    Since the latest up-date I can't see any movies.  It always returns to the main menu.  Is anyone else having this problem and how do I fix it?  We have gone 3 days without the use of renting movies.

    Welcome to the Apple Community.
    First you should try logging out of your iTunes Store account (settings > iTunes Store > accounts) and then back in again.
    If that doesn't help, try resetting the Apple TV (Settings > General > Reset > Reset all settings). You should also try restarting your router.
    If both of the above don't help, you should try a restore (Settings > General > Reset > Restore).

  • Iphone 5 keeps crashen an reboots after 3-4 mins have restored it an still re boots.i hav the latest up dates any help cheers.

    iphone 5 keeps crashen an reboots after 3-4 mins have restored it an still re boots.i hav the latest up dates any help cheers.

    PhotogYogi wrote:
    I Have the same issue on a brand new iPad mini 2. My battery is only lasting up to 5 hours. I went on chat with Apple last night and they said my battery is fine and its a Safari issue. I'm literally losing 1% every 3-4 minutes. I tried recalibrating my battery, signing out of iCloud, shutting off all locations, turning off background app refresh, restoring network settings, restoring all, and finally restoring from iTunes with no luck. This is just awful. I got this iPad so I could use it on my long flight for a trip I have coming up, and unfortunately, it's not going to last that long, plus I'm concerned about how many times i will be recharging my battery because of this since battery's do have a life cycle dependent on the number of charges. This is frustrating and needs to be fixed ASAP and addressed by Apple.
    By the way, Apple told me to bring my device to the Apple Store because it's still under warranty. That's great and all, but I'm going to waste my time if there is no fix for this issue.
    Ok so you want Apple to address the problem, but yet you don't want to take it to them just in case they can't fix it? What if they can fix it? Complaining here certainly won't fix it.

  • Were do i find the latest up dates for the 3g phone

    were do i find the latest up dates for the 3g phone

    On iTunes when you connect your iPhone. The latest version for the 3g is 4.2.1. What version do you have on your iPhone?

  • Query to find the  second maximum date in a table

    please give me the query to find the second maximum date in a table

    You can try with this
    SELECT empno
          ,hiredate
      FROM emp        a
    WHERE 2          = (SELECT COUNT(DISTINCT hiredate)
                           FROM emp        b
                          WHERE b.hiredate      >= a.hiredate
    OR
    SELECT empno
          ,hiredate
      FROM (SELECT ROWNUM      row_num
                  ,empno
                  ,hiredate
              FROM emp        a
          ORDER BY hiredate   ASC
    WHERE row_num             = 2;Regards
    Arun

  • How to get the latest Change date and time of a M.O. from View VIAUFKST

    Hi All,
    I want to get the latest date and time of a M.O. from view
    VIAUFKST. I have written the query like this...
      SELECT AUFNR
             AEDAT  " Changed Date
             AEZEIT " Changed Time
        FROM VIAUFKST
        INTO TABLE I_VIAUFKST
       WHERE AEDAT >= W_LASTRUN_DATE
       ORDER BY AEDAT DESCENDING.
    but its not giving me right results... Pls help me out on this or suggest me the right approach to achieve the same...As this is very critical issue...
    Advance Thanks and Points Gauranteed...
    Suresh

    > SELECT AUFNR
    >          AEDAT
    >          AEZEIT
    >     FROM VIAUFKST
    >     INTO TABLE I_VIAUFKST
    >    WHERE AEDAT >= W_LASTRUN_DATE.  
    >
    >   IF NOT I_VIAUFKST[] IS INITIAL.
    >    SORT I_VIAUFKST BY AEDAT AEZEIT DESCENDING.
    >    READ TABLE I_VIAUFKST INDEX 1.
    >   ENDIF.
    >
    > The above statement is giving me different results...
    > such as...
    >
    >  1. 30/11/2005 19:20:11
    >  2. 29/11/2005 22:10:09
    >  3. 30/11/2005 20:56:09
    >  4. 28/11/2005 23:10:09
    >
    > by using the above SORT statement i am getting the
    > fourth record as the latest, where as it should give
    > me the third record....
    >
    > Please advise,
    > Suresh.
    Hi Suresh,
    The reason why you are getting this result is because the system is interpreting the DESCENDING only for AEZEIT not for both. Change it to
    SORT I_VIAUFKST BY AEDAT DESCENDING AEZEIT DESCENDING

  • How to get the latest row from my Logical Table Source?

    Hi everyone,
    I have a SALARY_HISTORY table that holds the Salary Date and the Salary Amount for an employee, as a simple example. In my Business Model, I want to have a Display Folder called "Current Salary" and use the Where Clause restriction to derive the latest salary for each of my employees.
    In standard SQL Plus, I used a nested SQL statement, e.g. "where a.SalaryDate = (select max(b.SalaryDate) from SALARY_HISTORY b where b.employeeid = a.employeeid)".
    Is there anyway in the "Where Clause" filter of the LTS to derive this type of a query?
    I have tried things like "DB".""."SCHEMA"."AL_SALARY_HISTORY"."SalaryDate" = EVALUATE('SELECT_PHYSICAL MAX(SALARY_DATE) FROM "DB".."SCHEMA"."AL_SALARY_HISTORY" WHERE employeeid = %1)', "DB".""."SCHEMA"."AL_SALARY_HISTORY"."employeeid"). And I know I can't use any of the analytic functions in a where clause.
    So how do I go about this other than creating a View in the database or creating a function in the database to give me the maximum salary date for my employee?
    Thanks
    Paul

    Hi Paul,
    You could achieve this requirement using a sub query. Briefly, the steps are
    1. Just create one report with max(salary_date) for each employee.
    2. Create another report with SALARY_DATE included.
    3. Create a filter (Based on another analysis) on this report, as employee is in(Employee of report in step1) AND SALARY_DATE IS IN(SALARY_DATE of report in step1)(this is the max_salary_date for him)
    You could notice that BI Server would send two queries to the backend for this info.
    Hope this helps.
    Thank you,
    Dhar

  • How can i find the latest row inserted in a table

    i have a table with five columns and there is no primary key and everyday 100's of rows will be inserted to this table ,infact by mistake i have inserted a row and i just want to find out which is the last row i have inserted in to this particular table is there any way to find out this please......

    That's not guaranteed to give you the latest row added to the table. Oracle could place new rows anywhere depending on what happened to rows in the table previously, what space is available in the tablespace etc etc:
    SQL> create sequence dt_test_rowid_seq start with 1 increment by 1;
    Sequence created.
    SQL>--generate some test data
    SQL> CREATE TABLE dt_test_rowid as
      2  select     object_id,
      3     object_name,
      4     dt_test_rowid_seq.nextval ins_sequence
      5  from
      6     dba_objects
      7  where
      8     object_id is not null
      9  and
    10     rownum <10000;
    Table created.
    SQL>--here, the latest addition to the table....
    SQL> select max(ins_sequence) from dt_test_rowid;
    MAX(INS_SEQUENCE)
                 9999
    SQL>... reflects the highest rowid
    SQL> select ins_sequence from dt_test_rowid where rowid=(select max(rowid) from dt_test_rowid);
    INS_SEQUENCE
            9999
    SQL>--get rid of a load of rows
    SQL> delete from dt_test_rowid where mod(object_id,2)=0;
    2521 rows deleted.
    SQL>--insert a load more
    SQL> insert into dt_test_rowid
      2  select     object_id,
      3     object_name,
      4     dt_test_rowid_seq.nextval ins_sequence
      5  from
      6     dba_objects
      7  where
      8     object_id is not null
      9  and
    10     rownum <1000;
    999 rows created.
    SQL>--and here the latest addition to the table...
    SQL> select max(ins_sequence) from dt_test_rowid;
    MAX(INS_SEQUENCE)
                10998
    SQL>--...is NOT reflected by the highest rowid
    SQL> select ins_sequence from dt_test_rowid where rowid=(select max(rowid) from dt_test_rowid);
    INS_SEQUENCE
            9999

  • How to pull the Latest Time/Date of the update?

    Hi BW gurus,
    Hope everyone is fine.
    I have a doubt to meet my user requirement.
    I have a developed the infocubes and Infoset(combining only two master data infoprovider infoobjects) and created few reports on them.
    Now the requirement is
    "Client is asking for the latest date on which the data target is updated".
    Say if we run the infopackage on a particular day say "Dec 1st 2006"
    For example one cube is a full update, always by dropping the previously loaded data and one cube is updated with the delta update.
    For all the reports , if we run the query, the report should give the information stating that the latest update was made on "UPDATED DATE=Dec 1st 2006".
    how to achieve this?
    Please somebody help me out.
    Please tell me the step by step that I need to follow to achieve this.
    Any kind of help is appreciated.
    I am still in DEV.
    Thanks in advance,
    Regards
    Sam Mathew

    Hello
    This can be achieved
    First add an infoobject to your Data targets for Update date
    Second , include the update date infoobject in your infosource
    Map the infoobject with the field sys-datum which is current system date
    So whenever you execute an infopackage, the sys-datum field will pick up the current date at which it is executed.
    This is what you want in BW as latest update date of data target
    Regards
    Ganesh N

  • How to populate the webservice XML data in to Table  ODI- Webserice invoke

    Hi,
    I have multiple work orders in my oracle db table, That means multiple WorkOrder_Item_ID's are there in my source table. When I start transfer the data from source to Target using ODI , I need to get the information of multiple Work order Item_IDs from the Webservice response data ( XML data) of another system by calling ODI Webservice Invoke in ODI and insert the same Webservice XML response data in my source table in the corresponding Item_ID's.
    My First question : How can I take the data from Webservice XML and put in to correspoding Item relevent data in to Source Table
    Second question: How can I send the multiple work order item ID at the same time to the Webservice and insert the relevant item data in to Source table using ODI.
    Finally this combined soure table data should be moved to Target table in ODI.. That I know.. How to do it.
    Can any one please give answers for the above said two questions.
    Thanks,
    Rajesh
    Edited by: user11226287 on Oct 30, 2009 4:40 AM
    Edited by: user11226287 on Nov 1, 2009 10:44 PM
    Edited by: user11226287 on Nov 1, 2009 10:59 PM

    I find some words in the implementation guide, it says:"To collect data from your non-Oracle ERP systems or your trading partners' systems,you model each non-Oracle ERP system or trading partner as an Oracle Applications organization and store their setup and transaction data there".
    But I can't find where to model the application organization for the legacy system.
    anyone can give some clues? Thanks in advance.

Maybe you are looking for