Selecting single record from multiple record based on date

Hi experts,
I have a table which contains the multiple records for single ID No. Now i have to select single record which contains the latest date.
here is the structure
Name   Null Type        
ID_P        NUMBER      
NAME_P      VARCHAR2(12)
DATE_P      TIMESTAMP(6)
Records
1 loosi     22-AUG-13 01.27.48.000000000 PM
1 nammi  26-AUG-13 01.28.10.000000000 PM
2 kk        22-AUG-13 01.28.26.000000000 PM
2 thej      26-AUG-13 01.28.42.000000000 PM
now i have to select below 2 rows how can write select qurie for this?
1 loosi     26-AUG-13 01.27.48.000000000 PM
2 thej      26-AUG-13 01.28.42.000000000 PM

Hi,
You can use the analytic ROW_NUMBER function.
I don't have a copy of your table, so I'll use scott.emp to illustrate.  In scott.emp, there may be multiple rows for a single job.  To display just 1 row per job, the row with the most recent hiredate:
WITH got_r_num AS
     SELECT  empno, job, deptno, hiredate -- Or whatever columns you want
     ,       ROW_NUMBER () OVER ( PARTITION BY  job
                                  ORDER BY      hiredate DESC
                                )  AS r_num
    FROM    scott.emp
--  WHERE ...   -- If you need any filtering put it here
SELECT   *      -- Or list all columns except r_num
FROM     got_r_num
WHERE    r_num   = 1
What results do you want in case of ties?  Depending on your requirements, you may want to add tie-breaking expressions to the analytic ORDER BY clause, and/or use RANK instead of ROW_NUMBER.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
Point out where the query above is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
If you modify the query at all, post your modified version.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002

Similar Messages

  • Selecting single dataset from multiple datasets based on prioritized column

    I apologize if a similar question has been answered before. I don't seem to find to the correct search terms to find the solution.
    On to the question - I have the following data:
    +---ItemID---+---ItemName----------------------+---CompanyID---+
    |    1001    | Item  1001                      |       1       |
    |    1001    | Tuote 1001                      |       2       |
    |    1001    | Artikel 1001                    |       3       |
    |    1002    | Item  1002                      |       1       |
    |    1002    | Artikel 1002                    |       3       |
    |    1150    | Tuote 1150                      |       2       |
    |    2000    | Item  2000                      |       1       |
    |    2000    | Tuote 2000                      |       2       |
    |    2222    | Tuote 2222                      |       2       |
    |    2222    | Artikel 2222                    |       3       |
    +------------+---------------------------------+---------------+
    with t as (
            select 1001 ItemID, 'Item  1001' ItemName, 1 CompanyID from dual union all
            select 1001,    'Tuote 1001',   2 from dual union all
            select 1001,    'Artikel 1001', 3 from dual union all
            select 1002,    'Item  1002',   1 from dual union all
            select 1002,    'Artikel 1002', 3 from dual union all
            select 1150,    'Tuote 1150',   2 from dual union all
            select 2000,    'Item  2000',   1 from dual union all
            select 2000,    'Tuote 2000',   2 from dual union all
            select 2222,    'Tuote 2222',   2 from dual union all
            select 2222,    'Artikel 2222', 3 from dual
    select
    from
        tAs you can see, not all companies contain the same items. I would need to get a list which contains each itemid only once, and item name (and other fields not visible in the example) from the first company in which the item is found. The priority would be CompanyID 1, 3 and lastly 2. So the above example would result in the following list:
    +---ItemID---+---ItemName----------------------+---CompanyID---+
    |    1001    | Item  1001                      |       1       |
    |    1002    | Item  1002                      |       1       |
    |    1150    | Tuote 1150                      |       2       |
    |    2000    | Item  2000                      |       1       |
    |    2222    | Artikel 2222                    |       3       |
    +------------+---------------------------------+---------------+

    Hi,
    That's called a Top-N Query , and here's one way to do it:
    WITH     got_r_num   AS
         SELECT     ItemID, ItemName, CompanyID
         ,     ROW_NUMBER () OVER ( PARTITION BY  ItemID
                                   ORDER BY          CASE  CompanyID
                                                   WHEN  1  THEN  1
                                        WHEN  3  THEN  2
                                        WHEN  2  THEN  3
                                             END
                                 ) AS r_num
         FROM    t
    --     WHERE     ...     -- Any filtering goes here
    SELECT     ItemID, ItemName, CompanyID
    FROM     got_r_num
    WHERE     r_num     = 1
    ;The tricky part here is getting an expression that will sort the CompanIDs in the order in which you want them (3 comes before 2). If that order applies to other queries besides this one, then you should really not hard-code it into any query. Instead, add a column to the company table (or create a company table, if you don't already have one), that indicates the sort order, and join to that table.
    The aggregate KEEP (DENSE_RANK ...) feature could also be used to get these results, but you mentioned that there were "other fields not visible in the example", which means you would probably have to repeat a fairly complicated expression for each one of them. The query above is easily extended; add whatever columns you want to both SELECT clauses.
    Edited by: Frank Kulash on Jun 21, 2010 4:41 PM

  • Split single row in multiple rows based on date range

    I need sql script that can split single row in multiple rows based on start date and end date column in table.
    Thank you

    I agree to your suggestion of having a dates table permanently in the database. Thats how we also do for most of our projects as well
    But in most projects the ownership  of table creation etc lies with the client as they will be the DBAs and will be design approval authorities. What I've seen is the fact that though
    many of them are in favour of having calendar table they dont generally prefer having a permanent table for numbers in the db. The best that they would agree is for creating a UDF which will have
    tally table functionality built into it based on a number range and can be used in cases where we need to multiply records as above.
    Wherever we have the freedom of doing design then I would also prefer creating it as a permanent table with required indexes as you suggested.
    >> many of them are in favour of having calendar table they dont generally prefer having a permanent table
    Those people do not understand about database and are not DBAs :-)
    It is our job to tell them what is right or wrong.
    ** This is a real story! I had a client several years back, who was the CEO of a software company.
    He use the query:
    select * from table_name
    In order to get the last ID!
    The table_name was actually a view that took data from several tables, and the main table that he wanted to get the ID included several string columns, with lot of data!
    he actually pulled all this data to the application, just to get the lat ID in a specific table!
    It is our job as Consultants or DBAs to fix's his misunderstanding :-)
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • To select from database table based on date range

    hi
    i have a selection screen in which date range is being given
    say eg 23/06/07  to 23/12/08
    based on this date i want to select data from a ztable
    eg i want to select a field amount from table
    and three is a field date range on the table
    for this particular field i want to select all records for amount field  and factual field falling wiithing this date range and sum it
    eg
    based on date range as in selcetion screen
    select amount( field1)  factual ( field2) from ztable into it_ztable where date = ?....
    please give me code for it  and how to sum all values as i will get from the ztable into internal table the two values as fetched from the ztable
    please suggest asap
    regards
    arora

    hi
    i am using
    sELECT field1 field2 FROM Ztable  INto it_matu
                       where DATE GE sl_dat-low    
                        AND  DATE LE sl_dat-high.   
    i am getting data in internal table but
    say i have twelve records now i want to sum it the both the columns into and use that sum final amount to display
    let me know how to use sume in the intrranal tabl do i need to use control statement
    how to use the sum for two columns and take into a serperate variable to display
    regards
    aRora

  • How can I create a single order from multiple quotations?

    How can I create a single order from multiple quotations that I have created by the transaction VA21 ?
    Thanks in advance for the answers.

    hi
    Go to transaction: /nva01
    Enter order type : ZOR
    Sale org :xxxx
    Dist.channel:xx
    Division :xx
    Press enter
    Click on “Sale document” and select Create with reference
    Then enter 1st quotation number & click on “COPY” or “Selection list”. Then click on “Copy “.Then all line items which belong to quoation1 copy to order.
    Then,
    Click on “Sale document” and select Create with reference
    Then enter 2nd quotation number & click on “COPY” or “Selection list”. Then click on “Copy “.Then all line items which belong to quoation2 copy to order.
    Then,
    Click on “Sale document” and select Create with reference
    Then enter 3rd quotation number & click on “COPY” or “Selection list”. Then click on “Copy “.Then all line items which belong to quoation3 copy to order.
    Now save the sale document.
    Kindly give reward points
    Edited by: WISH on Mar 19, 2008 2:25 PM

  • How can i select some row from multiple row in the same group of data

    I want to select some row from multiple row in the same group of data.
    ColumnA        
    Column B
    1                  OK
    1                   NG
    2                   NG
    2                          NG
    3                          OK
    3                          OK
    I want the row of group of
    ColumnA if  ColumnB contain even 'NG'
    row , select only one row which  Column B = 'NG'
    the result i want = 
    ColumnA         Column B
    1                         NG
    2                   NG
    3                          OK
    Thank you

    That's some awful explanation, but I think this is what you were driving at:
    DECLARE @forumTable TABLE (a INT, b CHAR(2))
    INSERT INTO @forumTable (a, b)
    VALUES
    (1, 'OK'),(1, 'NG'),
    (2, 'NG'),(2, 'NG'),
    (3, 'OK'),(3, 'OK')
    SELECT f.a, MIN(COALESCE(f2.b,f.b)) AS b
    FROM @forumTable f
    LEFT OUTER JOIN @forumTable f2
    ON f.a = f2.a
    AND f.b <> f2.b
    GROUP BY f.a

  • Can i create a single image from multiple images in lightroom?

    Can i create a single image from multiple images in lightroom?

    Like a panorama, a composite or focus stack? Have you tried the Lightroom forum?
    Photoshop Lightroom

  • Any Tutorial / Sample to create Single PDF from multiple source files using PDF assembler in a watched folder process.

    Any Tutorial / Sample to create Single PDF from multiple source files using PDF assembler in a watched folder process. I have a client application which will prepare number of source files and some meta data information (in .XML) which will be used in header/footer. Is it possible to put a run time generated DDX file in the watch folder and use it in Process. If possible how can I pass the file names in the DDX. Any sample Process will be very helpful.

    If possible, make use of Assembler API in your client application instead of doing this using watched folder. Here are the Assembler samples :  LiveCycle ES2.5 * Programming with LiveCycle ES2.5
    Watched folder can accept zip files (sample : Configuring a watched folder to handle multiple input files and write results to a single folder | Adobe LiveCycle Blog ). You can also use execute script to create the DDX at runtime : LiveCycle ES2 * Application Development Using LiveCycle Workbench ES2
    Thanks
    Wasil

  • How do I create. A single PDF from multiple files? PDF pack on iOS

    How do I create. A single PDF from multiple files? PDF pack on iOS
    The primary reason I signed up for. PDF Pack was to create a single PDF from multiple image files and other PDFs .
    Is this possible? If so how
    thanks in advance
    rich

    Hi Rich,
    The combine files feature isn't available when you're using Reader for iOS. However, you can log on to the web interface at Adobe Acrobat.com using your Adobe ID and credentials, and use the Combine Files feature there.
    Please let us know if you need further assistance.
    Best,
    Sara

  • Single delivery from multiple Sales Orders

    Can you let me know how to create a Single DN if there are different parts to be shipped if the below satisfies,
    same ship-to-party
    same ship date
    thx,

    Hi Pri,
    To have single delivery from multiple Sales Orders you have 2 waysto do it.
    The prerequisites are,
    A. All sales orders should have same ship to Party
    B. Delivery due dates should be same.
    C. Incoterms should also be same.
    D. Shipping Point should be same.
    Once this is ensured, you can either
    1. Go to Tr. Code VL10A and execute the delivery document creation for the list of sales orders
    Or,
    2. Go to VL01N. Give 1st order no. enter into the overview screen
    Here, go to main menu, Outbound Delivery ---> Collective Processing- Del. Creation
    This will also take u to the same VL10A screen.
    Hope, this is helpful. Award points if found helpful.
    Regards,
    Niketan

  • Does OBIEE has ability to create a single cube from multiple data sources?

    Hi all,
    Does OBIEE has the ability to create a single cube from multiple sources and does it has the ability to join multiple cubes?
    Looking forward to ur reply.

    Hi
    OBIEE can join multiple data sources to make a single data model, but it's not a cube in the multi-dimensional sense like Essbase or Oracle OLAP.
    To be able to join datasources together they need to have a common dimension or FK relationship depending on what the source is and what you want to do with it.
    Ed

  • Is it possible to get the updated table records based on date & time.

    Is it possible to get the updated table records based on date & time in oracle.
    Thanks in advance.

    no, actually i am asking update records using 'UPDATE
    or DELETE' statement, but not insert statement.
    Is it possible?
    I think we can do using trigger on table, but problem
    is if i am having 20 tables means i have to write 20
    trigger. i don't want like this.Of course it's still possible, typically you'll find applications with a column LAST_UPDATE, probably a LAST_UPDATED_BY and so on column. You don't say what your business need is, if you just want a one of query of updates to particular records and have a recent version of Oracle, then flashback query may well help, if you want to record update timestamps you either have to modify the table, or write some code to store your updates in an audit table somewhere.
    Niall Litchfield
    http://www.orawin.info/

  • Multi-file Loading Single Package from Multiple Agents?

    hi,
    i am trying to load the Multiple files from(Interface-Load Multiple file to Oracle DB) a package. as this activity is done multiple loading files Name from single table.
    I just want to know that is there any solution to execute the single Package from Multiple Agents for Load Balancing from Single table. & if YES then refer any document????
    Regards,
    AMSII

    done.resovlesd my self

  • Select single time printer & multiple PR should come through that printer

    Hi friends,
    I am calling smartform in loop to print multiple Purchase Requisition. End user wants to select single time printer & multiple Purchase Requisition should come through that printer.
    I am calling my Smartform in a LOOP.
    How I will resolve this issue.
    Regards,

    Hi,
    Instead of driver programme write loop statement in the smartform.
    Aswarth

  • How to display data from a recordset based on data from another recordset

    How to display data from a recordset based on data from
    another recordset.
    What I would like to do is as follows:
    I have a fantasy hockey league website. For each team I have
    a team page (clubhouse) which is generated using PHP/MySQL. The one
    area I would like to clean up is the displaying of the divisional
    standings on the right side. As of right now, I use a URL variable
    (division = id2) to grab the needed data, which works ok. What I
    want to do is clean up the url abit.
    So far the url is
    clubhouse.php?team=Wings&id=DET&id2=Pacific, in the end all
    I want is clubhouse.php?team=Wings.
    I have a separate table, that has the teams entire
    information (full team name, short team, abbreviation, conference,
    division, etc. so I was thinking if I could somehow do this:
    Recordset Team Info is filtered using URL variable team
    (short team). Based on what team equals, it would then insert this
    variable into the Divisional Standings recordset.
    So example: If I type in clubhouse.php?team=Wings, the Team
    Info recordset would bring up the Pacific division. Then 'Pacific'
    would be inserted into the Divisional Standings recordset to
    display the Pacific Division Standings.
    Basically I want this
    SELECT *
    FROM standings
    WHERE division = <teaminfo.division>
    ORDER BY pts DESC
    Could someone help me, thank you.

    Assuming two tables- teamtable and standings:
    teamtable - which has entire info about the team and has a
    field called
    "div" which has the division name say "pacific" and you want
    to use this
    name to get corresponding details from the other table.
    standings - which has a field called "division" which you
    want to use to
    give the standings
    SELECT * FROM standings AS st, teamtable AS t
    WHERE st.division = t.div
    ORDER BY pts DESC
    Instead of * you could be specific on what fields you want to
    select ..
    something like
    SELECT st.id AS id, st.position AS position, st.teamname AS
    team
    You cannot lose until you give up !!!
    "Leburn98" <[email protected]> wrote in
    message
    news:[email protected]...
    > How to display data from a recordset based on data from
    another recordset.
    >
    > What I would like to do is as follows:
    >
    > I have a fantasy hockey league website. For each team I
    have a team page
    > (clubhouse) which is generated using PHP/MySQL. The one
    area I would like
    > to
    > clean up is the displaying of the divisional standings
    on the right side.
    > As of
    > right now, I use a URL variable (division = id2) to grab
    the needed data,
    > which
    > works ok. What I want to do is clean up the url abit.
    >
    > So far the url is
    clubhouse.php?team=Wings&id=DET&id2=Pacific, in the end
    > all
    > I want is clubhouse.php?team=Wings.
    >
    > I have a separate table, that has the teams entire
    information (full team
    > name, short team, abbreviation, conference, division,
    etc. so I was
    > thinking if
    > I could somehow do this:
    >
    > Recordset Team Info is filtered using URL variable team
    (short team).
    > Based on
    > what team equals, it would then insert this variable
    into the Divisional
    > Standings recordset.
    >
    > So example: If I type in clubhouse.php?team=Wings, the
    Team Info recordset
    > would bring up the Pacific division. Then 'Pacific'
    would be inserted into
    > the
    > Divisional Standings recordset to display the Pacific
    Division Standings.
    >
    > Basically I want this
    >
    > SELECT *
    > FROM standings
    > WHERE division = <teaminfo.division>
    > ORDER BY pts DESC
    >
    > Could someone help me, thank you.
    >

Maybe you are looking for

  • Corrupted/Locked out apple ID "An Unknown Error has occurred" logging into support?

    I was forced to use a different apple id to log into this support community because all attempts from different devices and browsers using another ID have ended up at the password prompt with "An unknown error has occurred" at the community login scr

  • Can't Find iLife after Password Change

    I bought a used MacBookPro with OS X 10.5.6 installed fresh. On initial startup I set up my Account. The computer wouldn't recognize any passwords initially. Had to change Administrator's Password. Prior to this iLife applications were on this comput

  • Things You Need To Know about old= New iMac

    1) Your HP All-In-One printer/scanner/copier - will it work with this new Leopard iMac? Maybe. I struggled with the all-in-one Printer Scanner Copier PSC 2355 for hours, and that includes reading the discussion forums on Apple's website. Apple suppor

  • Direct connection between 2 SPA9000

    I'm considering on buying SPA9000. My question is: is it possible setup a call through 2 different SPA9000 located on different site directly, without using ITSP intermediary. Can a line on one SPA9000 be set to register to a line on another? Can I u

  • Mac Mail v4.1 stalls after attaching a Word document

    I have had intermittent trouble when attaching a Word doc onto an email. Right after the attachment is made, if I click back into the email body to continue typing, Mail stalls. This has occurred since the upgrade to Snow Leopard.