How to read only the most current records in PL/SQL

Oracle version: 11.2
I have a table in ORACLE called RATES and there is a EFFECTIVE_DATE, RATE_NAME, RATE_AMOUNT
RATE
1 RATE_ONE 1/1/2000 0.10
2 RATE_ONE 5/1/2005 0.15
3 RATE_ONE 12/1/2010 0.20
4 RATE_TWO 10/15/2009 0.33
5 RATE_THREE 9/7/2011 0.05
6 RATE_THREE 12/31/2011 0.06
A rate can be in there multiple times, but the most recent rate is the active rate. I need to query this table and only want to bring back the currently active rows:
RECORDS 3, 4 and 6
How can I do this in the most elegant way?
Can I say:
SELECT RATE WHERE trunc(sysdate) between EFFECTIVE_DATE and trunc(sysdate);
(this will not work. I'm not sure how to do this without an exp date column and then I could say
SELECT RATE WHERE trunc(sysdate) between EFFECTIVE_DATE and END_DATE
The problem is that I cannot add that column at this time, so need to find a way to do it programatically
Edited by: userLynx on Feb 1, 2012 8:56 AM

Try This:
WITH a
        AS (SELECT 'RATE_ONE' ratename,
                   TO_DATE ('1/1/2000', 'mm/dd/yyyy') eff_date,
                   0.10 amount
              FROM DUAL
            UNION ALL
            SELECT 'RATE_ONE' ratename,
                   TO_DATE ('5/1/2005', 'mm/dd/yyyy') eff_date,
                   0.15 amount
              FROM DUAL
            UNION ALL
            SELECT 'RATE_ONE' ratename,
                   TO_DATE ('12/1/2010', 'mm/dd/yyyy') eff_date,
                   0.20 amount
              FROM DUAL
            UNION ALL
            SELECT 'RATE_TWO' ratename,
                   TO_DATE ('10/15/2009', 'mm/dd/yyyy') eff_date,
                   0.33 amount
              FROM DUAL
            UNION ALL
            SELECT 'RATE_THREE' ratename,
                   TO_DATE ('9/7/2011', 'mm/dd/yyyy') eff_date,
                   0.05 amount
              FROM DUAL
            UNION ALL
            SELECT 'RATE_THREE' ratename,
                   TO_DATE ('12/31/2011', 'mm/dd/yyyy') eff_date,
                   0.06 amount
              FROM DUAL)
SELECT ratename, eff_date, amount
  FROM (SELECT ratename,
               eff_date,
               amount,
               RANK () OVER (PARTITION BY ratename ORDER BY eff_date DESC) rk
          FROM a)
WHERE rk = 1

Similar Messages

  • How to return only the most recent row?

    Hi guys,
    I have a question which I am hoping is not too difficult but I just am not sure how to do it. I need to run a query on a table which may bring back multiple rows for my criteria, however I only want to bring back 1 of these multiple rows and the one I want to bring back has to be the most recent. I do have a date_created column on my table as well as a date_last_updated column. So basically using the select statement below as an example this query could return lets say 5 rows, I however only want it to return the most recent row and the most recent row is determined by the date_last_updated (which will only be populated if the record has been updated otherwise it is null) or the date_created fields.
    select * from my_table
    where model_id = 234
    Any help on this matter would be greatly appreciated.
    Thank you.

    Hi,
    you can do; -
    select *
    from
    (select *
    from my_table
    order by creation_date desc)
    where rownum = 1This does not guarantee that you will get the most recent in cases of records being created at exactly the same time, but if your table has a prime key then you could use this as the order by to get the same effect, though if say 5 records are inserted as a batch what does it really mean to be inserted last....
    regards,
    Robert.
    Edited by: Robert Angel on 09-Jul-2012 08:22 to add code tags.

  • How to highlight lines of ALV of the most current delimited records?

    Hi all,
    I used the ALV to display annual salary records of certain employees. Now the ALV will show the past annual salary as well as the most current records. I need to highlight all the current records. Anyone have any idea on this? Thanks

    You need to add a field into your output table for the color
    example
    data: begin of tb_out occurs 0,
    line_color(4) type c,
    end of tb_out.
    Then, in your build layout form
    gd_layout-info_fieldname =      'LINE_COLOR'.
    When you build your output table, you fill the field LINE_COLOR with the color you want to use (you can choose a standard color for everything, like C100, and a different color for the row you want to highlight, like C300).

  • How to get Most current record in the reporting

    Hi All,
    I have reporting requiremnt  like to get the most recent record.
    Please see the below example we have 3 records but with 2 different sales represtentatives assigened to the same document.but i need to get most recently assigned sales representative record  that is number 2(10726056 and status open).
    Now i am geeting the 2 open records .Need to get only one.we do not have any other difference in the records to keep track of the sales representatives assignment to get the new sales rep id other than request id.
    Can any one tell me  most rcurrent data varibles under the request id do.Will it solves my issues o r any other ideas please welcome.
    Customer No    Sales rep    Doc number    Status     Request id
    0000613086    10726056    9000783660       C            REQU_1
    0000613086    10726056    9000783660       O            REQU_1
    0000613086    10182679    9000783660       O            REQU_2

    Hi Sirisha,
    it seems to be a problem of the kind "exception aggregation" , but let me say it can result in a very complex solution.
    What about using a Virtual Infoprovider with servicecs to solve the issue?
    You should create an additional InfoCube that reads form the basic one (where you have data) and then you should "delete" invalid records considering the request number.
    By the way time stamp seems to be the easier solution.
    Hope it helps
    GFV

  • I have uninstalled and reinstalled the most current edition of Adobe Reader, including the patch. When I open a PDF file, the screen is first grey, then viewable, but the message "Adobe Reader has stopped working" comes up. How do I remedy this?

    I have uninstalled and reinstalled the most current edition of Adobe Reader (11.9), including the patch. When I open a PDF file, the screen is first grey, then viewable, but then the message "Adobe Reader has stopped working" comes up. How do I remedy this?

    RR,
    One thing often tried first is to create a new document and File>Place the corrupted one to see how much may be rescued that way (remember to tick Paste remembers Layers in the Layer palette flyout/dropdown first, and to untick it afterwards).
    Here is a website where you can see whether it can rescue the file, and if it can, you may pay for a subscription to have it done,
    http://www.recoverytoolbox.com/buy_illustrator.html
    and another similar website,
    http://markzware.com/adobe-software/fix-illustrator-file-unknown-error-occurred-pdf2dtp-fi le-recovery/
    As far as I remember, the former is for Win and the latter for Mac.
    Here are a few pages about struggling with it yourself:
    http://daxxter.wordpress.com/2009/04/16/how-to-recover-a-corrupted-illustrator-ai-file/
    http://helpx.adobe.com/illustrator/kb/troubleshoot-damaged-illustrator-files.html
    http://kb2.adobe.com/cps/500/cpsid_50032.html
    http://kb2.adobe.com/cps/500/cpsid_50031.html
    http://helpx.adobe.com/illustrator/kb/enable-content-recovery-mode-illustrator.html
    Failing a full recovery, hopefully you have one or more earlier versions and/or bits of artwork saved before it happened.

  • Since downloading the most current iTunes software I can no longer print the insert (label) for a jewel case.  The songs are printed over each other and can not be read.  Any suggestions?  Thanks.

    Since downloading the most current iTunes software I am no longer able to print an insert (label) for a jewel case.  I click on print, choose jewel case and then it doesn't matter which option I choose for the insert it will only print the songs over each other in a 1 inch section so that it can not be used or read.  If instead of clicking on the jewel case I click on list it works fine and prints an appropriate list.  I have always updated the iTunes software the first time I am offered to do so and I have never had a problem printing the jewel case inserts.  Since this issue is not about a piece of hardware iTunes help will not help me. 

    Did you ever get a response?
    If you so how did you correct the problem?
    I have the exact problem you had.
    Please let me know.
    Thank you
    <Edited by Host>

  • Using sender file adapter to read the most current file

    Hi,
    in my sender file adapter , i have to read the latest file- all files in  the source directory are named as <filename><timestamp>.txt . I need to read the file with the latest timestamp (i.e. the most current file )
    How do i configure this using file adapter.
    thanks

    Hi Sreeram,
    thanks for the answer- but i found that the option can only be used with NFS transport protocol. what if i am using FTP ?
    alos, by date option means- files are processed according to their time stamp in the file system, starting with the oldest file.
    However in my case i only want to read the latest file and ignore the older files.
    Thanks

  • Update once only most current record that meets conditions

    Want to only allow the most current date with the stateID of 1 to update once and not update after the intial update when running sql code over again. 
    changeTypeID containerID    stateID dateEntered                               note
    UPDATE          900172-0800  5       2014-09-23 04:38:29.313            Pallet #71809
    UPDATE          900172-0800  1       2014-11-20 09:17:51.017 
    UPDATE          900172-0800  10      2014-11-24 15:03:32.177   900172-0800->Destroyed
    UPDATE          900172-0800  10      2014-11-24 15:04:00.777   900172-0800->Destroyed
    UPDATE          900172-0800  10      2014-11-24 15:05:44.763   900172-0800->Destroyed
    SELECT containerID
    INTO #Temp
          ContainerHistory
          WHERE dateEntered >= DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP) -1, 0)
            AND dateEntered < DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
            AND stateID = 1 ORDER BY dateEntered DESC ????
    UPDATE ContainerStates
      SET stateID = 10,
       dateEntered = getdate(),
       note = containerID + '->Destroyed'
      WHERE containerID IN (
       SELECT barCode AS containerID FROM #Temp WHERE containerExpired = 1

    >> Want to only allow the most current date with the state_id of 1 to update once and not update after the initial update when running SQL code over again. <<
    Please follow basic Netiquette and post the DDL we need to answer this. Do you know how to follow industry and ANSI/ISO standards? You should follow ISO-11179 rules for naming data elements. You hjave noi idea what that means.  Avoid dialect in favor of
    ANSI/ISO Standard SQL. 
    There is no such attribute as a “change_type_id” in RDBMS. You can have a “<something>_id” “<something>_type” but not a weird mix of attribute proprieties. Likewise, “state_id” makes no sense. If you meant a status, then you need two dates to show
    when that state of being applied to the entity. 
    To track the history of, say, Foobars we need to see time as a continuum and model it as (begin_date, end_date) pairs that define when a foobar had a particular value. Here is the skeleton. 
    CREATE TABLE Foobar_History 
    (foo_id CHAR(9) NOT NULL, 
     start_date DATE NOT NULL, 
     end_date DATE, --null means current 
     CHECK (start_date <= end_date),
     foo_status INTEGER NOT NULL, 
     PRIMARY KEY (foo_id, start_date)); 
    When the end_date is NULL, that state of being is still current. You use a simple query for the status on any particular date;
    SELECT * 
      FROM Foobar
     WHERE @in_cal_date
         BETWEEN start_date
          AND COALESCE (end_date, CURRENT_TIMESTAMP);
    There are more tricks in the DDL to prevent gaps, etc
    CREATE TABLE Events
    (event_id CHAR(10) NOT NULL,
     previous_event_end_date DATE NOT NULL  
     CONSTRAINT Chained_Dates  
      REFERENCES Events (event_end_date), 
     event_start_date DATE NOT NULL, 
     event_end_date DATE UNIQUE, -- null means event in progress
      PRIMARY KEY (event_id, event_start_date), 
     CONSTRAINT Event_Order_Valid 
      CHECK (event_start_date <= event_end_date), 
     CONSTRAINT Chained_Dates 
      CHECK (DATEADD(DAY, 1, previous_event_end_date) = event_start_date)
    -- CHECK (previous_event_end_date + INTERVAL '01' DAYS) = event_start_date)
    -- disable the Chained_Dates constraint
    ALTER TABLE Events NOCHECK CONSTRAINT Chained_Dates;
    GO
    -- insert a starter row
    INSERT INTO Events(event_id, previous_event_end_date, event_start_date, event_end_date)
    VALUES ('Foo Fest', '2010-01-01', '2010-01-02', '2010-01-05');
    GO
    -- enable the constraint in the table
    ALTER TABLE Events CHECK CONSTRAINT Chained_Dates;
    GO
    -- this works
    INSERT INTO Events(event_id, previous_event_end_date, event_start_date, event_end_date)
    VALUES ('Glob Week', '2010-01-05', '2010-01-06', '2010-01-10');
    -- this fails
    INSERT INTO Events(event_id, previous_event_end_date, event_start_date, event_end_date)
    VALUES ('Snoob', '2010-01-09', '2010-01-11', '2010-01-15'); 
    What you did post is awful. Why did you append “->Destroyed” to an identifier? This is redundant AND destroys the integrity of the original encoding. Why do you use a local temp table? This mimics a  1950's scratch tape and no SQL programmer would use
    it. Why would a note repeat another column? 
    Please read this and try again. 
    https://www.simple-talk.com/sql/t-sql-programming/state-transition-constraints/
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How do I update from OS X 10.5.8 to the most current OS for using iCloud?

    I need help with upgrading from OS X 10.5.8 to whatever the most current OS.

    Depends on which model iMac you have?
    see > How to identify iMac models
    First off, does your iMac meet the Processor and RAM spec's for Snow Leopard?
    see > Mac OS X v10.6 Snow Leopard - Technical Specifications
    If so, then you must upgrade to Snow Leopard before you can get Lion or Mountain Lion from the App Store.
    Again, providing that your iMac meets the spec's for them as well?
    see > OS X Lion - Technical Specifications
    see > Apple - OS X Mountain Lion - Read the technical specifications.

  • I can't update my iPad because it says that i have the most current version of software but i only have iOS 5.1.1. what can i do?

    i can't update my iPad because it says that i have the most current software but its only 5.1.1. what can i do?

    Get a newer device. The original iPad can't be updated past 5.1.1.
    (120544)

  • How to get the most current file based on date and time stamp using SSIS?

    Hello,
    Let us assume that files get copied in a specific directory. We need to pick up a file and load data. Can you guys let me know how to get the most current file based on date and time stamp using SSIS?
    Thanks
    thx regards dinesh vv

    hi simon
    i excuted this script it is giving error..
       Microsoft SQL Server Integration Services Script Task
       Write scripts using Microsoft Visual C# 2008.
       The ScriptMain is the entry point class of the script.
    using System;
    using System.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    namespace ST_9a6d985a04b249c2addd766b58fee890.csproj
        [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
        public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
            #region VSTA generated code
            enum ScriptResults
                Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
                Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
            #endregion
            The execution engine calls this method when the task executes.
            To access the object model, use the Dts property. Connections, variables, events,
            and logging features are available as members of the Dts property as shown in the following examples.
            To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
            To post a log entry, call Dts.Log("This is my log text", 999, null);
            To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
            To use the connections collection use something like the following:
            ConnectionManager cm = Dts.Connections.Add("OLEDB");
            cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
            Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
            To open Help, press F1.
            public void Main()
                string file = Dts.Variables["User::FolderName"].Value.ToString();
                string[] files = System.IO.Directory.GetFiles(Dts.Variables["User::FolderName"].Value.ToString());
                System.IO.FileInfo finf;
                DateTime currentDate = new DateTime();
                string lastFile = string.Empty;
                foreach (string f in files)
                    finf = new System.IO.FileInfo(f);
                    if (finf.CreationTime >= currentDate)
                        currentDate = finf.CreationTime;
                        lastFile = f;
                Dts.Variables["User::LastFile"].Value = lastFile;
                Dts.TaskResult = (int)ScriptResults.Success;
    thx regards dinesh vv

  • How can I use documents created in Pages 08 with the most current version of pages?

    I just upgraded to the most current version of Pages from Pages 08.  However, none of my files created with Pages 08 will open.  I am told that I first need to save them with Pages 09, but I don't have Pages 09.  What can I do to convert these files into a format that works with the newest Pages?

    I have the same problem. There are a couple of clumsy workarounds. One is to open your file with Pages 08 and export it as a Word document, then import it into Pages 5. The second one is to open the file in Pages 08, copy the contents to the clipboard and paste it into Pages 5.

  • How do I rectify the issue that AE (CC) won't import mov files on Windows 8.1.  (It's the most current Quicktime).

    How do I rectify the issue that AE (CC) won't import mov files on Windows 8.1.  (It's the most current Quicktime).

    troubleshooting QuickTime errors with After Effects

  • For Multi value attributes, how we can view only the most recent value?

    Where we can set what in endeca servers (MDEX, Clover & Studio) to view only the most recent value of a multi assign value attribute on Studio server?

    That's correct, multi-value attributes do not support this in Endeca.
    If you're looking to do it, I would keep writing your updates to the multi-value attribute (to maintain the functionality that depends on this attribute and its multiple values) and also write it to a separate single-value that is constantly being updated, rather than appended to.
    Something like:
    One attribute called MyValueMulti as a multi-assign.
    AND
    One attribute called MyValueLatest as a single-assign.
    Regards,
    Patrick Rafferty
    http://branchbird.com

  • My iphone 4 is stalling a lot. I've had it for a year now, I have the most current OS, it's not too full of apps, or anything like that. Many times throughout the day, I cannot switch from app to app, unless I do a complete power-off. Any ideas?

    I've had it for a year now.
    I have the most current OS. I snyc it to my itunes 2-3 times a week. It is only about 25% full. It stalls (I don't know if I would call it freezing) between trying to switch from app to app. I either have to let it sit there for a few minutes, or turn it all the way off and turn it back on.
    And yes, I know to press the home button twice to get the bottom part activated. That's not working. I'm not sure if this is a common thing, or what with iphone 4's.
    Anyone got any ideas?

    Thanks for that information!
    I'm sure I will be calling AppleCare, but the problem is, they charge for the phone calls don't they? Because I don't have money to be spending to be on the phone with a support service.
    In other things, it seemed like the only time my MacBook was working was when I had Snow Leopard without the 10.6.8 update download that was supposed to be done to prepare for OS X Lion.
    When I look at the information of my HD it says that I have 10.6.8 but that was the install that it claimed to have failed and caused me to restart resulting in all of the repeated problems.
    Also, because my computer is currently down, and I've lost all files how would that effect the use of my iPhone? Because if it doesn't get fixed by the time OS 5 is released, how would I be able to upgrade?!

Maybe you are looking for

  • How can CRM trigger event of R/3

    Hello Folks, My requireemnt I need to run a workflow in R/3 which will be triggered by CRM. Can you give me a breif how we link CRM with R/3.    Is it only with RFC.    Or can we dirctly trigger a event of R/3 from CRM. Please let me know the details

  • Difference between ECC 6.0 & SAP 4.7

    Hi Can anybody help in explaining the difference between ECC 6.0 and SAP 4.7. I wanted the detailed difference between these two. You can reach me at [email protected] Thanks & Regards Nisad

  • Saved File w/same name: Rescue old one?

    Hello; I'm an experienced user, can't believe I did this. Saved a DVDSP file in same folder with FCP file. Used same file name. Wrote DVDSP file, lost FCP file. I know data is still there, but now name in directory points to DVDSP file. Any suggestio

  • Microsoft Run time Errors

    Each time I open PSE 9 I recieve a Microsoft Visual C++ runtime error. Does any know how to fix this?

  • Legend disappear when resizing graph in CVI 2009

    Hi forum, i have a problem with the graph control and the legend of a graph. I want to resize a graph by using the splitter. I attach the graph to two splitters to resize it in width and height by doubleclicking the panel. If the legend is in the ran