Group by clause get the last row of max occurence

Table 1
Division Incident
1 xyz
2 abc
3 efg
1 klo
2 jkl
I want to have an sql query which groups the occurrences of (division) in the table. If two grouping counts are same, it should give largest division.. division 1 and 2 have 2 occurrences each.
select div, count(*) FROM TABLE1 GROUP by division is not giving the result.
I am trying to get division 2 as the answer. No other rows should be present in the return

mat wrote:
Table 1
Division Incident
1 xyz
2 abc
3 efg
1 klo
2 jkl
I want to have an sql query which groups the occurrences of (division) in the table. If two grouping counts are same, it should give largest division.. division 1 and 2 have 2 occurrences each.
select div, count(*) FROM TABLE1 GROUP by division is not giving the result.
I am trying to get division 2 as the answer. No other rows should be present in the return
select division
from
select division, incident, row_number() over (order by count_per_div desc, division desc) as rn
from
   select division, incident, count(*) over (partition by division) as count_per_div
   from <your_table>
where rn = 1;Would be one way (not tested since you didn't provide sample data I could run this against).
You could probably combine that in to less steps, but as is it shows you the steps to take.
Cheers,

Similar Messages

  • Cant get the last row in jtable

    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
            //creating the table
        for (i=0;i<this.rows;i++)
         model.insertRow(i,new Object[]{"input Y1:",""});
                for ( i=i;i<this.Amount+this.rows;i++)
         model.insertRow(i,new Object[]{"input Amount:",""});
    //end of creatingthis code creats the table that i need and its works right.
    for(i=0;i<rows;i++){
                  fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
            int j=0;
            String s=GetData(table, 1, 4).toString();
            //the problem line
            String s1=GetData(table, 1, 5).toString();
        public Object GetData(JTable table, int col_index, int row_index){
        return table.getModel().getValueAt(row_index, col_index);
      }this line i get ""
    String s1=GetData(table, 1, 5).toString();
    Edited by: vitaly87 on 00:41 08/04/2011

    vitaly87 wrote:
    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
    this line i get ""
    String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
    If it hadn't found the row, I expect you would have got an Exception
    Winston

  • How to get the last row of a database table.

    HI ,
    I want to get record exactly from the last row of a database table.
    How is that possible?

    Hi,
    To fetch last record from an internal table, just do find the number of records in it and read using index.
    DESCRIBE TABLE ITAB LINES L_LINES.
    READ TABLE ITAB INDEX L_LINES.
    You can also use LOOP .. ENDLOOP but the above method is better (performance wise).
    using LOOP .. ENDLOOP.
    LOOP AT ITAB.
    **do nothing
    ENDLOOP.
    **process ITAB (Header record of ITAB).
    **after ENLOOP, ITAB will have the last record of the internal table.
    [here ITAB is internal table as well as header record.]
    But what is the requirement?
    If you are looking for the current record of an employee then you can use ENDDA = HIGH_DATE.
    My advice is to review your requirement again and try to fetch only that record which you need.
    Mubeen

  • How to get the last row in a resultset or query

    Hi All
    Say If I have a complex query which returns a resultset say 15 rows. Now I want to limit the output showing only the last row.
    How can we do this

    Keep in mind Oracle does not keep "row" order as such. Unlike a graphical type db like Access, Oracle will not always give you back the results in order.
    Even if you were to use a sequence, your query is never guaranteed to give back the results in the order you are expecting. You must then give an order by statement to all queries expecting the order.
    Your definition of last row too is vague - if it is in fact the greatest amount, use the inline view suggestion. If you simply want to see the last inserted row, consider adding a last_update_date column inserting the sysdate (by a trigger perhaps). This would then allow you to see the last inserted row.
    Enjoy!

  • How to get the last row

    I have 10 rows in my table and I have to retrive last row using rownum.
    For this I use
    SELECT * from <table_name>
    where rownum<=10
    minus
    SELECT * from <table_name>
    where rownum<=9
    The result is no rows selected
    In the same case if I use
    SELECT rownum from <table_name>
    Where rownum <= 10
    minus
    SELECT rownum from <table_name>
    where rownum <=9
    The result is 10
    Why this happend.
    If the result is 10, then why the row whose rowid is 10 is not retrived

    All
    Please bear in mind that ROWNUM is an attribute of the query NOT the table. The last row returned by an unORDERed SELECT statement may be the most recently inserted row but is not guaranteed to be so.
    The only way of assuring yourself of returning the most recent row is either to timestamp all your tables with a date_created column or to use a primary key with an ascending value.
    rgds, APC

  • Trying to get the last row from a resultset

    Hi,
    I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
    My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
    I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
    I've tried a variety of things and most seem to return the first row, not showing the updated values.
    Or, if it does work, it takes to long to load, and i get an error.
    here is the working code;
    Object m = machCBX.getSelectedItem():
    try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
    ResultSet.TYPE_SCROLL_INSENSITIVE,  //tried both INSENSITIVE and SENSITIVE
    ResultSet.CONCUR_READ_ONLY);
    last.setString(1, String.valueOf(m));
    rs. = last.executeQuery();
    if(rs.isAfterLast) == false ) {
    rs.afterLast();
    while(rs.previous()) {
    String p = rs.getString("part");
    int c = rs.getInt("count");
    partJTX.setText(p);
    countJTX.setText(c);
    }this grabs values, but they are not the last entered values.
    Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
    Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
    I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
    thanks
    -PD

    OK, you've got a major misunderstanding...
    The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
    Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
    In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
    While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course).

  • HELP! How te retrieve the last row in MYSQL database using Servlet!

    Hi ,
    I am new servlets. I am trying to retireve the last row id inserted using the servlet.
    Could someone show me a working sample code on how to retrieve the last record inserted?
    Thanks
    MY CODE
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class demo_gr extends HttpServlet {
    //***** Servlet access to data base
    public void doPost (HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
         String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
              String param1 = req.getParameter("param1");
              PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");
              String semail, sfname, slname, rfname, rlname, remail, message;
              int cardType;
              sfname = req.getParameter("sfname");
              slname = req.getParameter("slname");
              rfname = req.getParameter("rfname");
              rlname = req.getParameter("rlname");
              semail = req.getParameter("semail");
              remail = req.getParameter("remail");
              message = req.getParameter("message");
              //cardType = req.getParameter("cardType");
              cardType = Integer.parseInt(req.getParameter("cardType"));
              out.println(" param1 " + param1 + "\n");
         String query = "SELECT * FROM greeting_db "
    + "WHERE id =" + param1 + "";
              String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
              query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
              //out.println(" query2 " + query2 + "\n");
              if (semail.equals("") || sfname.equals("") ||
              slname.equals("") || rfname.equals("") ||
              rlname.equals("") || remail.equals("") ||
              message.equals(""))
                        out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
                        out.close();
                        return;
              String title = "Your Card Has Been Sent";
              out.println("<BODY>\n" +
    "<H1 ALIGN=CENTER>" + title + "</H1>\n" );
                   out.println("\n" +
    "\n" +
    " From  " + sfname + ", " + slname + "\n <br> To  "
                                            + rfname + ", " + rlname + "\n <br>Receiver Email  " + remail + "\n<br> Your Message "
                                            + message + "\n<br> <br> :");
                   if (cardType ==1)
                        out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
                   else if(cardType ==2) {
                        out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
                   else if(cardType ==3) {
                        out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
    else if(cardType ==4) {
                        out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
    else if(cardType ==5) {
                        out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
    else if(cardType ==6) {
                        out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
    out.println("</BODY></HTML>");
         try {
              Class.forName ("com.mysql.jdbc.Driver");
              Connection con = DriverManager.getConnection
              ( url, "*****", "******" );
    Statement stmt = con.createStatement ();
                   stmt.execute (query2);
                   //String query3 = "SELECT LAST_INSERT_ID()";
                   //ResultSet rs = stmt.executeQuery (query3);
                   //int questionID = rs.getInt(1);
                   System.out.println("Total rows:"+questionID);
    stmt.close();
    con.close();
    } // end try
    catch (SQLException ex) {
              //PrintWriter out = resp.getWriter();
         resp.setContentType("text/html");
              while (ex != null) { 
         out.println ("SQL Exception: " + ex.getMessage ());
         ex = ex.getNextException ();
    } // end while
    } // end catch SQLException
    catch (java.lang.Exception ex) {
         //PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");     
              out.println ("Exception: " + ex.getMessage ());
    } // end doGet
    private void printResultSet ( HttpServletResponse resp, ResultSet rs )
    throws SQLException {
    try {
              PrintWriter out = resp.getWriter();
         out.println("<html>");
         out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
         out.println("<body>");
         out.println("<center><font color=AA0000>");
         out.println("<table border='1'>");
         int numCols = rs.getMetaData().getColumnCount ();
    while ( rs.next() ) {
              out.println("<tr>");
         for (int i=1; i<=numCols; i++) {
    out.print("<td>" + rs.getString(i) + "</td>" );
    } // end for
    out.println("</tr>");
    } // end while
         out.println("</table>");
         out.println("</font></center>");
         out.println("</body>");
         out.println("</html>");
         out.close();
         } // end try
    catch ( IOException except) {
    } // end catch
    } // end returnHTML
    } // end jbsJDBCServlet

    I dont know what table names and fields you have but
    say you have a table called XYZ which has a primary
    key field called keyID.
    So in order to get the last row inserted, you could
    do something like
    Select *
    from XYZ
    where keyID = (Select MAX(keyID) from XYZ);
    Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
    This works fine if the emp_id is incremental and of type integer
    Query:
    select      *
    from      employee e,  (select max(emp_id) as emp_id from employee) z
    where      e.emp_id = z.emp_id
    or
    select top 1 * from employee order by emp_id descUday

  • How to get the last transaction in a row in SQL Developer?

    What syntax would I use to get the last transaction of a row in SQL developer?
    The way I have my query set-up currently it is not returning the correct data, here is my current syntax:
    select ssn, max(tran_id), chng_type,tran_id
    from pda_tran
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type,tran_id;
    It returns a 'C' chng_type but it is not the last one. when I query on this ssn this is what I get:
    ssn tran_id chng_type
    xxx-xxx-0011 001 A
    xxx-xxx-0011 002 E
    xxx-xxx-0011 003 C
    xxx-xxx-0011 004 S
    xxx-xxx-0011 005 C
    xxx-xxx-0011 006 T
    I only want to return the ssn's with a last transaction chng_type of 'C'. How can I get the correct information returned. Please advise.

    From what I see and read... there is one to many group by
    You wrote
    select ssn, max(tran_id), chng_type,tran_id
    from pda_tran
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type,tran_id;
    If you want the max(tran_id), remove it from the "group by"
    select ssn, chng_type, max(tran_id)
    FROM
    (SELECT 'xxx-xxx-0011' ssn, '001' tran_id, 'A' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '002' tran_id, 'E' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '003' tran_id, 'C' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '004' tran_id, 'S' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '005' tran_id, 'C' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '006'tran_id, 'T' chng_type FROM DUAL )
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type;

  • Getting the first row for each group

    Hi Everyone,
    I have a query which returns a number of rows, all of which are valid. What I need to do is to get the first row for each group and work with those records.
    For example ...
    client flight startairport destairport stops
    A fl123 LGW BKK 2
    A fl124 LHR BKK 5
    B fl432 LGW XYZ 7
    B fl432 MAN ABC 8
    .... etc.
    I would need to return one row for Client A and one row for Client B (etc.) but find that I can't use the MIN function because it would return the MIN value for each column (i.e. mix up the rows). I also can use the rownum=1 because this would only return one row rather than one row per group (i.e. per client).
    I have been investigating and most postings seem to say that it needs a second query to look up the first row for each grouping. This is a solution which would not really be practical because my query is already quite complex and incorporating duplicate subqueries would just make the whole thing much to cumbersome.
    So what I really new is a "MIN by group" or a "TOP by group" or a "ROWNUM=1 by group" function.
    Can anyone help me with this? I'm sure that there must be a command to handle this.
    Regards and any thanks,
    Alan Searle
    Cologne, Germany

    Something like this:
    select *
    from (
       select table1.*
       row_number() over (partition by col1, col2 order by col3, col4) rn
       from table1
    where rn = 1In the "partition by" clause you place what you normally would "group by".
    In the "order by" clause you define which will have row_number = 1.
    Edit:
    PS. The [url http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/functions004.htm#i81407]docs have more examples on using analytical functions ;-)
    Edited by: Kim Berg Hansen on Sep 16, 2011 10:46 AM

  • Get rows where the last row finish off

    Hi, i have two tables AND would LIKE TO get data BY combining both.
    here IS my data
    WITH hist AS
      SELECT To_Date('4/23/2010','mm/dd/yyyy') dt, 999 alias, 'PROC' dom FROM dual UNION ALL
      SELECT To_Date('4/27/2010','mm/dd/yyyy') dt, 999 alias, 'LON' dom FROM dual UNION all
      SELECT To_Date('4/1/2010','mm/dd/yyyy') dt, 111 alias, 'SOC' dom FROM dual UNION all
      SELECT To_Date('4/10/2010','mm/dd/yyyy') dt, 111 alias, 'NAO' dom FROM dual UNION ALL
      SELECT To_Date('3/23/2010','mm/dd/yyyy') dt, 222 alias, 'PSE' dom FROM dual
    final AS
      SELECT To_Date('2/26/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION ALL
      SELECT To_Date('4/22/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION all
      SELECT To_Date('4/26/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION ALL
      SELECT To_Date('4/30/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION ALL
      SELECT To_Date('2/25/2010','mm/dd/yyyy') dt, 111 alias FROM dual UNION ALL
      SELECT To_Date('2/26/2010','mm/dd/yyyy') dt, 222 alias FROM dual UNION ALL
      SELECT To_Date('4/22/2010','mm/dd/yyyy') dt, 222 alias FROM dual UNION all
      SELECT To_Date('4/26/2010','mm/dd/yyyy') dt, 222 alias FROM dual
    the output should be as follow(without the extra blank line of course)
    DT           ALIAS   DOM
    2/26/2010     999     PROC
    4/22/2010     999     PROC
    4/26/2010     999     LON
    4/30/2010     999     LON
    4/27/2010     999     LON
    4/23/2010     999     PROC
    2/25/2010     111     SOC
    4/1/2010     222     SOC
    4/10/2010     222     NAO
    2/26/2010     222     PSE
    4/22/2010     222     PSE
    4/26/2010     222     PSEso what i am doing here is as follow, take one row in hist table (4/23) and join with final table and give me all rows in final table
    where dt <= to the row in hist table and include the row from hist table.
    this logic will give me rows 2/26/2010,4/22/10 4/23/2010
    then the second row in hist table (4/27/2010) wiill get all rows
    in final table that is <= to the current row and pick up the rows starting from the row > than the last row where the 4/23/2010 finished off
    in this case the output will be 4/26/10, 4/27/2010(we need to include row from hist)
    since there is no row in hist that is greater than 4/30/2010, this date will still be display and dom column value should be taking from the max date in hist
    which is 4/27/2010. see output above
    this sound a little confusing to explain but look at output of what to expect as output. the other ids should follow the same logic
    can someone help write a query for this? thanks

    Hi,
    Devx wrote:
    Frank, thanks again, i ran the query in oracle 11g and oracle 9i. 11g runs ok but 9i doesnt. it looks like the ignore null option is not supported in 9i. That's right: IGNORE NULLS was new in Oracle 10. You should always mention your Oracle version whenever you ask a quiestion, especially if it's as old as Oracle 9.
    i will be running this query in 9i. is there any alternative to re-write this query without using last value since ignore null is not supported and the output is not as i expected when i take that keyword out.
    i really appreciate your help. please let me know how would i re-write the query. thanksOne work-around is to use LEAD or LAG instead of LAST_VALUE. This means you have to know exactly where (how many rows away) the most recent non-NULL value is, which in turn requires other analytuic funtions, such as ROW_NUMBER, and more sub-queries:
    WITH     combined_tables        AS
         SELECT     dt, alias, NVL (dom, '_?_') AS dom     FROM hist
         UNION
         SELECT     dt, alias, NULL          AS dom      FROM final
    ,     got_r_num     AS
         SELECT     dt, alias, dom
         ,     ROW_NUMBER () OVER ( PARTITION BY  alias
                                   ORDER BY          dt
                           )               AS r_num
         ,     COUNT (*)     OVER ( PARTITION BY  alias
                           )               AS alias_cnt
         FROM    combined_tables
    ,     got_skip_cnts     AS
         SELECT     dt, alias, dom, r_num
         ,     r_num - MAX (CASE WHEN dom IS NOT NULL THEN r_num END)
                                 OVER ( PARTITION BY  alias
                               ORDER BY          r_num
                             )                    AS skip_before
         ,     MIN (CASE WHEN dom IS NOT NULL THEN r_num END)
                                 OVER ( PARTITION BY  alias
                               ORDER BY          r_num     DESC
                             ) - r_num               AS skip_after
         FROM    got_r_num
    ,     got_next_dom     AS
         SELECT     dt, alias, dom, r_num, skip_before
         ,     LEAD (dom, skip_after) OVER ( PARTITION BY  alias
                                                ORDER BY      r_num
                                 ) AS next_dom
         FROM    got_skip_cnts
    SELECT       dt
    ,       alias
    ,       NULLIF ( COALESCE ( next_dom
                            , LAG (dom, skip_before) OVER ( PARTITION BY  alias
                                                         ORDER BY         r_num
               )     AS dom
    FROM       got_next_dom
    ORDER BY  alias
    ,            dt
    ;You should be able to calculate bot LEAD and LAG in the same query, but there seems to be a bug that only calculates one of them correctly in this case. The sub-query got_next_dom gets around that, by doing the LEAD in a separate sub-query.

  • Need to query the database to get the last sequence number

    Hi all
    I am trying to get the last sequence number of the last row inserted into my Oracle database. Please could someone give me the SQL which would allow me to do this - using Oracle SQL Explorer I have confirmed that there is a sequence on the table which is called: XYZ_SEQ and the code for this is:
    CREATE SEQUENCE "MY_USER_NAME"."XYZ_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 21 CACHE 20 NOORDER NOCYCLE ;
    My Java application is inserting a row into my table and to insert a new row I need to have the last sequence inserted +1 so the new row can be added.
    Any help would be much appreciated.

    Hi,
    Welcome to the forum!
    If you are using a sequence just do (example):
    INSERT INTO TABLE_NAME
       (COL1,
        COL2)
    VALUES
       (SEQUENCE_NAME.NEXTVAL,
        OTHER_VALUE);to obtain (and use) the next number in the sequence when you are inserting.
    If you have a sequence to use for a specific table, you should use it when your insert new data (no matter your are doing that: java application, procedure, etc). Doing this you avoid some problems when you have the sequence 'out of date' about the associated data.
    Regards,
    Edited by: Walter Fernández on Sep 19, 2009 10:08 AM
    Edited by: Walter Fernández on Sep 19, 2009 10:10 AM

  • How to get the last value edited by users from JTable?

    Hi.
    I have a JDialog that includes an editable JTable. This table is used to set up field caption and font for a report program. I found only when cursor is moved to another cell, the value in current cell being edited will be transferred to Table Model. So if the user don�t move cursor to another cell after editing the value of a cell but click OK button directly, Table Model cannot get the last value edited by the user, I wonder if there is a way to fire JTable to transfer the value being edited to Table model.
    By the way, I found if the TableCellEditor is using JCheckBox or JComboBox instead of JTextField, there is no this problem.
    Thank you for any reply.

    I guess you can make use of the following methods on your table model to inform it make it getValueAt bcos table data has changed.
    fireTableCellUpdated
    Notifies all listeners that the value of the cell at [row, column] has been updated.
    fireTableChanged
    Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model.
    fireTableDataChanged
    Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.
    But when to call these methods??
    -- When OK button is pressed, do this as the first thing!!
    OR
    -- Call this on every key event!!
    regds,
    CA

  • How to get the last different occurrence in a SCD table

    hey,
    i have a slowly changing dimension and i want to get the last different occurrence for each row.
    Sample Data
    the field LAST_VALUE is the one i'm looking for.
    ID     START_DATE     END_DATE     VALUE     LAST_VALUE
    1     01/01/2000     01/02/2000     X     null
    1     01/02/2000     01/03/2000     X     null
    1     01/03/2000     01/04/2000     Y     X
    1     01/04/2000     01/05/2000     Y     X
    1     01/05/2000     01/06/2000     X     Y
    1     01/06/2000     01/07/2000     X     Y
    1     01/07/2000     01/08/2000     Z     X
    1     01/08/2000     01/09/2000     Q     Z i want to try and do that without three sub selects.
    i've tried analytic functions but lag brings me the last occurrence which is not necessarily different.
    thanks.

    Something like this :
    SQL> with sample_data as (
      2    select 1 ID, to_date('01/01/2000','DD/MM/YYYY') START_DATE, to_date('01/02/2000','DD/MM/YYYY') END_DATE, 'X' VALUE from dual union all
      3    select 1, to_date('01/02/2000','DD/MM/YYYY'), to_date('01/03/2000','DD/MM/YYYY'), 'X' from dual union all
      4    select 1, to_date('01/03/2000','DD/MM/YYYY'), to_date('01/04/2000','DD/MM/YYYY'), 'Y' from dual union all
      5    select 1, to_date('01/04/2000','DD/MM/YYYY'), to_date('01/05/2000','DD/MM/YYYY'), 'Y' from dual union all
      6    select 1, to_date('01/05/2000','DD/MM/YYYY'), to_date('01/06/2000','DD/MM/YYYY'), 'X' from dual union all
      7    select 1, to_date('01/06/2000','DD/MM/YYYY'), to_date('01/07/2000','DD/MM/YYYY'), 'X' from dual union all
      8    select 1, to_date('01/07/2000','DD/MM/YYYY'), to_date('01/08/2000','DD/MM/YYYY'), 'Z' from dual union all
      9    select 1, to_date('01/08/2000','DD/MM/YYYY'), to_date('01/09/2000','DD/MM/YYYY'), 'Q' from dual
    10  )
    11  select v.id
    12       , v.start_date
    13       , v.end_date
    14       , v.value
    15       , last_value(case when value != prev_value then prev_value end ignore nulls)
    16               over(partition by id order by start_date) as "LAST_VALUE"
    17  from (
    18    select t.*
    19         , lag(value) over(partition by id order by start_date) as prev_value
    20    from sample_data t
    21  ) v
    22  ;
            ID START_DATE  END_DATE    VALUE LAST_VALUE
             1 01/01/2000  01/02/2000  X    
             1 01/02/2000  01/03/2000  X    
             1 01/03/2000  01/04/2000  Y     X
             1 01/04/2000  01/05/2000  Y     X
             1 01/05/2000  01/06/2000  X     Y
             1 01/06/2000  01/07/2000  X     Y
             1 01/07/2000  01/08/2000  Z     X
             1 01/08/2000  01/09/2000  Q     Z
    8 rows selected

  • How to get the last inserted record from a table ?

    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

    I'm not sure about 8i features.
    I assume here that you don't have 'Date-Time' stamp columns on the table which is the easiest way to determine the last inserted row in the table.
    If not try the following :-
    select address, piece, SQL_TEXT
    from V$SQLTEXT
    where upper(sql_text) like '%INSERT INTO TABLE_NAME%'
    Substiute the TABLE_NAME with the name of the actual table.
    Have fun.
    Regards,
    Shailender
    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

  • How to get the "last changed by" for a set of function modules?

    How to get the "last changed by" for a set of function modules?
    is there any table to get it??

    See [this|Re: Date of creation of function module] I posted earlier.
    >TFDIR will give you the name of the function group program and the include number.
    >E.g. SAPLZFUNCGROUP Include 01.
    >From this you can construct the include name: LZFUNCGROUPU01.
    >You can look this up in TRDIR to find the creation date (CDAT) of the function module.
    In your case, you need unam and udat.
    matt

Maybe you are looking for

  • Read-only files and folders

    I would like to add ilustrations to mp3 files that I adeed to my iTunes library. However, some of the iTunes folders seem to be read-only. I tried to uncheck them but when I restart iTunes they are read-only again. Any advice ?

  • RAID Configurations for Cisco servers

    Hi All, What is the RAID configuration for Cisco Appliance(Version 8.5) like CUCM, CUPS, CUIC, Unity etc?RAID Configuration will be done while installtion itself or we need to do it explicitly? Regards, Adithya

  • Property "OK Code Field" for SAP Transaction iViews

    Hi there, I created an SAP Transaction iView which is accessing an ECC system using SAP GUI for Html. In the properties of the iView I found the property "OK Code Field" - has anybody a idea how this field is used? I hope that there is a possibility

  • Error in Application Integrator

    Hi, I am trying to implement the Application Integrator on EP 6, SR1 Release. The following error is seen during runtime. An exception occurred while processing a request for : iView : N/A Component Name : N/A Unable to lookup System 'SysAlias'. Plea

  • HT1420 where can i view all my authorized devices and then deathorize one of them

    Where can I view my authorized devices and then deauthorize one of them without deauthoriveing all of them ?