Best way to select distinct values based on another column?

I have a table with three columns: id (NUMBER), data_dt (DATE), and data_value (NUMBER).
There is a primary key on id and data_dt.
I want to select the record with the latest data_dt for each unique id.
What is the best way to do this?
I have three different methods, but there may be something I am missing.
First:
SELECT *
FROM
  SELECT id, data_dt, data_value,
         FIRST_VALUE(data_dt)
         OVER (PARTITION BY id ORDER BY data_dt DESC) AS last_data_dt
  FROM the_table
WHERE data_dt = last_data_dt;(I use ORDER BY...DESC instead of just ORDER BY so I don't need the ROWS BETWEEN clause)
Second:
SELECT t1.*
FROM the_table t1
JOIN
  SELECT id, MAX(data_dt) AS last_data_dt
  FROM the_table
  GROUP BY id
) t2 ON (t2.id = t1.id AND t2.data_dt = t1.data_dt);Third:
SELECT t1.*
FROM the_table t1
WHERE t1.data_dt =
  SELECT MAX(t2.data_dt)
  FROM the_table t2
  WHERE t2.id = t1.id
);-- Don

Hi,
There are more possible scenario's, for example:
select t1.*
from   the_table t1
where not exists ( select null
                   from   the_table t2
                   and    t2.data_dt > t1.data_dt
What is the best way to do this?Only you can tell:
Test all scenario's, check the execution plans, set timing on and pick the best/fastest one ;-)
If it's not clear, please post the execution plans here.

Similar Messages

  • Best way to create a table based on another table

    Hello,
    I am trying to create a table based on another table with all the data in it. It has large data.
    create table <tablename> as select * from table1.
    Is this the best way of doing it or is there any other way. please advice.
    thanks

    I am suggested to create new table as
    create table <newtable> as
    select * from <oldtable> where rownum < 1;
    then
    alter table <newtable> compress;
    then
    insert /*+ append */ into <newtable> as select * from <oldtable>;
    but i getting an error saying missing values key words ora- 00926.
    please advice

  • What's the best way to define some values based on the URL?

    Let's say for example I want all my URLs for servlets to take the form:
    http://mysite.com/module/action?arguments
    What's the most scalable way to handle mapping the values in place of "module" and "action"? For example, I might have a "forum" module and have an action to "deleteThread", called like so:
    http://mysite.com/forum/deleteThread?id=321
    I know I can just parse it myself, but is there a better way to handle this via some settings in web.xml or similar? All my requests go through a Front Controller which needs to know which module and action have been requested so that it can run the appropriate action controller.
    Cheers,
    Chris

    At the risk of repeat-posting, I'll clarify. Say I create a file named routing.xml which defines some routes like this:
    <routing-config>
      <route>
        <name>Standard rule</name>
        <description>
          This route maps the first two parts in the path with the module and action
        </description>
        <url-pattern>/:module/:action.do</url-pattern>
      </route>
      <route>
        <name>Default Index</name>
        <description>
          Allows the module to be specified without the action for "Index" actions.
        </description>
        <url-pattern>/:module.do</url-pattern>
        <request-parameters>
          <parameter key="action" value="Index" />
        </request-parameters>
      </route>
      <route>
        <name>Homepage</name>
        <description>
          Loads the Home page
        </description>
        <url-pattern>/</url-pattern>
        <request-parameters>
          <parameter key="module" value="Home" />
          <parameter key="action" value="Index" />
        </request-parameters>
      </route>
    </routing-config>The bits like ":module" which be represented by the actual name of the module in the URL. Does anyone know if something like this already exists? :)
    I wrote this exact same thing in PHP5 just a few weeks ago but I really don't have the motivation to write it all over again in Java :P On a side-note, things like this usually come with helpers for turning unclean URIs into clean URIs.

  • How to re-calculate a column value based on another column value in the same ADF Table row

    Hi,
    I'm using Jdeveloper 11.1.2.3.0.
    I have an adf table with 2 columns, columnA and columnB.
    When the value changed in ColumnA,
    1) i need to call a PLSQL and update the ColumnB value that is returned from PLSQL.
    2) Show a warning message if the existing value in ColumnB is different from the one that is returned from PLSQL.
    Can anybody suggest how can i accomplish this?
    Thanks,
    Vinod

    hi user,
    if you have inputtext means have a valuechangelistener
    in that call your pl/sql function supply input value to the appropriate function then grab the result of the function. then bind the column inputtext and compare with it. then raise your warning using FacesMessage classes.
    Sameh Nassar: Create PL/SQL Function And Call It From Your ADF Application

  • Programatically Assigning Column Value Based on Another Column

    I have a problem as follows:
    My database table has the following setup:
    There may be many gift numbers the same, however many different recipient numbers for each gift.
    The receipient number should increment from 1-X based on the gift number, for example, if the gift number is the same then the receipient number should increment for that gift.
    Gift Number
    Recipient Number
    1
    1
    1
    2
    1
    3
    2
    1
    3
    1
    3
    2
    The programmatic code for inserting a new row would be:
    Check if gift number already exsists in database.
    -if it does exsist then find latest and increment current receipient number by one for receipment number
    -if it does not exsit set receipient number at 1
    How do i do this?
    JDEV - 11.1.2.4 (ADF BC)

    Your use case has some flaws which you should think about before trying to implement it.
    1) think about what happens if multiple users try to insert a record at the same time. What can happen? How do you want to handle this situation?
    2) do you really need the number to be gap less? The use case can be implemented easily if you don't have this restriction.
    3) The table should have the technical primary key to avoid pk clashes due to multiple inserts at one time.
    Now, if you have a technical pk as primary key, you can setup a unique key on both of the other columns which prevents that somehow you get duplicates there.
    You let the user insert the gift number and calculate the recipient number as max(recipient number)+1. Then you commit the record. If you don't get an error you are finished, if you get an error you add 1 to the recipient number and try to commit again, until the insert works.
    Timo

  • Change column value based on another

    Hi, everyone.
    my version 11.1.2.2.0.
    i wanna change 1 column's value based on another column's value that be selected.
    ex: select 2rd column to 'A' , then the 1rd should be 'New Start'.
    i used EL like #{row.bindings.MacdType.inputValue eq 1 ? 'New Start' :  row.bindings.CircuitId.inputValue}.
    But it does not set the inputvalue which should binding with the DataSource.
    what's the best way to do these logic?
    pls help. thx

    Hi,Abhijit;
    ex: the frist column is a LOV, the user select "A" for the first column, so the value of the second column should be changed to 'New Start'.
    And the value should be binding to the DC, when save, the value of the 2rd column should be saved to DB.
    thx

  • Best way to extract XML value wiith an xpath

    Hello,
    I wonder what is the best way to extract text value from XmlType with an xpath.
    I need to insert a row inside a table where the row's data come from xpath extractions of an XmlType. I do a lot of (approximative 20) :
    EXTRACTVALUE(var.myxmltype , '/an/xpath/to/extract/elem1').
    EXTRACTVALUE(var.myxmltype , '/an/xpath/to/extract/elemI').
    EXTRACTVALUE(var.myxmltype , '/an/xpath/to/extract/elem20').
    inside the insert statement
    Is this way is the best or is there a more optimal way ?
    For example extracting the node '/an/xpath/to/extract/' and sarting from this node extracting "elem1", ... , "elemI", "elemN" children.
    Thanks for your help,
    Regards,
    Nicolas

    Hi Nicolas,
    The answer depends on your actual storage method (binary, OR, CLOB?), and db version.
    You can try XMLTable, it might be better in this case :
    SELECT x.elem1, x.elem2, ... , x.elem20
    FROM your_table t
       , XMLTable(
          '/an/xpath/to/extract'
          passing t.myxmltype
          columns elem1  varchar2(30) path 'elem1'
                , elem2  varchar2(30) path 'elem2'
                , elem20 varchar2(30) path 'elem20'
         ) x
    ;

  • Need of SQL query in selecting distinct values from two tables

    hi,
    I need a query for selecting distinct values from two tables with one condition.
    for eg:
    there are two tables a & b.
    in table a there are values like age,sex,name,empno and in table b valuses are such as age,salary,DOJ,empno.
    here what i need is with the help of empno as unique field,i need to select distinct values from two tables (ie) except age.
    can anybody please help me.
    Thanks in advance,
    Ratheesh

    Not sure what you mean either, but perhaps this will start a dialog:
    SELECT DISTINCT a.empno,
                    a.name,
                    a.sex,
                    b.salary,
                    b.doj
    FROM    a,
            b
    WHERE   a.empno = b.empno;Greg

  • Best way to get the values of local variables

    What is currently the best way to get the values of local variables. I know it is not currently possible to set watchpoints on local variables, but what are the best workarounds?

    You have to use StackFrame methods, eg, visibleVariables and getValues. To get a StackFrame for a thread, that thread has to be suspended, eg, by a BreakpointEvent.

  • Best way to change TreeMap value?

    Hello,
    I am wondering what is the best way to change a value in a TreeMap? I have retrieved a value by .get on the key i.e.
    String aString = (TreeMap) aTreeMap.get(aKey);but would now like to change aString and ?.put? it back into the map?
    How would I do this?
    Thank you,
    Poot.

    but would now like to change aString and ?.put? it
    back into the map?Do I just have to keep a note on the (key,value) - especially key - change the value and then .put(key,value) back in? Though I'll need to remove the initial pairing if I do this since TreeMap won't allow duplicate keys!
    There must be an easier way as this.
    Thank you for your reply,
    Regards,
    Poot.

  • Count Distinct based on another column in the same table

    Hello,
    My question in short: is is it possible to add a new column to a view which holds the DISTINCT COUNTS of values/domains of another column in the same view?
    For example, in the below table the column "Distinct Count of Occurence" shows how many distinct values a person has in the Occurence column. So AAA has 1 and 2 therefore it is 2 distinct values etc.
    My issues is that I can retrieve unique values bu Count (Select Occurence)but I can not add the new column that would add the records to the corresponding Persons in the above table.
    Is there an easy way to achieve this on the DWH level or should it be done with MDX in the cube?
    Thanks

    Hi,
    Below a solution to use the view by adding a column with window functioning, maybe this will help.
    CREATE TABLE #TMP
    PERSON VARCHAR(10),
    OCCURENCE SMALLINT
    --DROP TABLE #TMP
    INSERT INTO #TMP(PERSON,OCCURENCE)
    VALUES
    ('AAA','1'),
    ('AAA','2'),
    ('BBB','1'),
    ('BBB','1'),
    ('BBB','1'),
    ('CCC','1'),
    ('CCC','2'),
    ('CCC','3');
    --TRUNCATE TABLE #TMP
    WITH CTE
    AS
    SELECT PERSON
    ,OCCURENCE
    ,ROW_NUMBER() OVER(PARTITION BY PERSON ORDER BY OCCURENCE) AS RN
    FROM #TMP
    SELECT PERSON, MAX(RN) AS RN
    FROM CTE
    GROUP BY PERSON
    Regards,
    Reshma
    Please Vote as Helpful if an answer is helpful and/or Please mark Proposed as Answer or Mark As Answer when question is answered

  • I burned a playlist to a data CD using itunes 11 but what is best way to get it import it into another computer with itunes running?

    I burned a playlist to a data CD using itunes 11 but what is best way to get it import it into another computer with itunes running?  I get an "X" when trying to copy to the "automatically add to itunes" folder on the 2nd computer.

    ok... so i i just made sure all my music is all together in 1 folder and i am going to trash my old music folder that is in the itunes folder... and follow your directions - let itunes start w/new library and bring my music in. Well, last little hurdle/question. I noticed that the place where my itunes library is - on an external drive doesnt have much space left on it. The place where i gathered all my music together in order to start fresh - is a different external drive and has LOTS of free space on it.
    SO... i now would like to just keep all that freshly compiled clean music right where it is but in advanced preferences I want to point to that new folder on the drive that has so much more space. So... should i delete the old music then go into itunes with a blank library and change the folder in preferences - quit and go back in and then follow your steps to loading my music? If i change the setting of where itunes looks for the music - that doesn't wipe out the old stuff... it just mixes it all up together right? I dont want that!!
    i promise this is the last question - i would love to fix this problem tonight and just be DONE!
    Thanks in advance for your patience and knowledge!!
    Lisa

  • Best way to move data and programs to another profile on same Mac?

    Hello,
    What is the best way to move data and programs to another profile on the same Mac? I have a user who's profile is corrupt, I know that most programs will work on both the new and old profile however when trying to copy the Desktop folder, or Documents folder I am getting permissions denied.
    Sort of like weeding a garden, I'm hoping I do not have to pick the data in each folder and copy individually.
    Thanks for your help!
    Johnathon

    This usually means that a configuration or preference file is corrupted.  In this user's /Home/Library/Preferences/ folder locate any preference files associated with iLinc and drag to the Trash.
    I would also check in the /Home/Library/Caches/ folder for a file or folder associated with iLinc and delete as well.
    See if the problem is resolved in the user's normal account.
    It's not that you cannot copy data from account to account, but doing so causes a lot of permissions issues that must be resolved.  The MacFixit article I linked above shows what you need to do after transferring from one account to another in order to change permissions on the "foreign" files to those of the destination account.

  • What is the best way to migrate your Adobe software to another computer?

    What is the best way to migrate your Adobe software to another computer?

    If you know that you do not intend to use the software on the old machine (especially if you are getting rid of it), the minimum you need to do is deactivate it.  That will disable use of it and free up an extra activation for you should you ever wish to have two machines available to use it on.  To deactivate you just open an application and choose Help -> Deactivate.  If this happens to be a Creative Suite, doing that to just one of the applications will deactivate the entire Suite.
    You can also uninstall the software if you like, but be sure to deactivate it first.

  • How to Fill list in excel based on another columns cell value

    Hello,
    I am facing issue while binding data to list i want to bind list or filter list based on another columns cell value

    If your list is a series of rows with column headers like the following:
    Column A
    Column B
    1
    Apple
    1
    Banana
    1
    Orange
    2
    Pineapple
    2
    Cucumber
    2
    Watermelon
    Then you can do this will Excel's built in filter functions. If you select the entire data table and then go to "DATA" then click the "FILTER" button a drop down will appear next to both headers (Column A and Column B in this case). You
    can then select the data you would like filtered from either column and Excel will hide that entire row.
    If this is not what you are looking for please post some examples of what you are trying to see.

Maybe you are looking for

  • Virtual Mail Setup - imapd-ssl error unknown protocol

    Hi, I have been relentlessly trying to setup my first email server and I think that I am almost there. I have been following the guide at: https://wiki.archlinux.org/index.php/Simple_Virtual_User_Mail_System I have followed it step by step and I'm 99

  • Creating a separate apple id/password for a single devise that is already registered

    I am having a terrible time managing the family's devices on iTunes.  I was trying to use one apple id and password for all, but when i last synced all of my devices, my contacts and calendar events were all replaced with my 15 year old son's!  I spe

  • Errors that I Can't get rid of?!

    Hello, I'm new to this community and have a question. Not sure if this is the right place to ask, but it's worth a try. So, I got a call from lenovo inc. somewhere in New Jersey (let's be serious please) and they told and showed me that there are a b

  • XSLT Debugger is disabled in Visual Studio 2013 Integrated Shell

    According to this link, the Visual Studio 2013 Integrated Shell contains an XSLT Debugger: https://msdn.microsoft.com/en-us/library/bb129445.aspx?f=255&MSPPError=-2147217396 I installed this version clean on a machine that has no prior Visual Studio

  • Default Buttons

    Hi, I've got a simple application that needs a custom "search" dialog. I've created a subclass of JDialog and it comes up just fine... Basically I have a JTextField for them to put in the search, a few checkboxes for the options, and two buttons at t