Getting correct  row from cartestian join..

I have two tables that look like. The two tables have key and date as columns which for a composite primary key :-
table1
key date
1     dt2
1     dt3
1     dt4
table2
key date
1     dt0
1     dt1
1     dt3
left outer join on table1.
if matching date is not there then i need to get values from row in table2 whose date is less than date in table1
For example, lets consider the table above... The desired output is:
table1 has 1,dt2 for which i have to take value from table2 : 1,dt1 (not from dt0 or dt03).

Somthing like this?
/*TEST DATA*/
with table1 as (
  select 1 key, trunc(sysdate, 'MONTH')+2 dt from dual UNION ALL
  select 1 key, trunc(sysdate, 'MONTH')+3 dt from dual UNION ALL
  select 1 key, trunc(sysdate, 'MONTH')+4 dt from dual),
     table2 as (
  select 1 key, trunc(sysdate, 'MONTH') dt from dual UNION ALL
  select 1 key, trunc(sysdate, 'MONTH')+1 dt from dual UNION ALL
  select 1 key, trunc(sysdate, 'MONTH')+3 dt from dual)
  /* END TEST DATA*/
select table2.key, table1.dt, max(table2.dt)
from table1, table2
where table1.key= table2.key
and table1.dt >= table2.dt
group by table2.key, table1.dt;
KEY                    DT                        MAX(TABLE2.DT)           
1                      03/MAR/07                 02/MAR/07                
1                      05/MAR/07                 04/MAR/07                
1                      04/MAR/07                 04/MAR/07                
3 rows selected

Similar Messages

  • How to get multiple rows from database table?

    hello !
    I need to get multiple rows from a OLEDB database table and display them on a table object.
    I did "Wrap in subfrom" on the table,  set  subform of the table to "flowed", and checked "Repeat row for each data item" of Row1 of the table.
    But I can get only one row on the table object.
    I need your help.
    Thanks

    Hi,
    best practices when deleting multiple rows is to do this on the business service, not the view layer for performance reasons. When you selected the rows to delete and press submit, then in a managed bean you access thetable instance (put a reference to a managed bean from the table "binding" property") and call getSeletedRowKeys. In JDeveloper 11g, ADF Faces returns the RowKeySet as a Set of List, where each list conatins the server side row key (e.g. oracle.jbo.Key) if you use ADF BC. Then you create a List (ArrayList) with this keys in it and call a method exposed on the business service (through a method activity in ADF) and pass the list as an argument. On the server side you then access the View Object that holds the data and find the row to delte by the keys in the list
    Example 134 here: http://blogs.oracle.com/smuenchadf/examples/#134 provides you with the code
    Frank

  • How to get first row from View Object cache.

    hi,
    I am using Jdeveloper 11.1.1.6
    can we get first row from View Object cache??
    Thanks in Advance.
    Best
    Shashidhar

    Hi Frank,
    Thanks for reply!!
    My case is:
    I have a Query based ViewObject.
    One of the field is LOV and remaining fields are in ADF table. the LOV field is out side ADF table when i insert first record in ADF table and i choose LOV  filed the value is selected.
    when i create second row LOV value got refreshed because both are in same VO.
    I need to get the LOV value of first row and set same value to second Row.
    Shashidhar

  • How to get specific rows from the vo or Iterator in the backing bean?

    Hi,
    I have to get the specific number of rows from iterator in the backing bean. means i want to get the records from the VO or Iterator only from 5 th record to 10th record its like rownum in SQL.
    We can use rownum in VO sql query. but there would be a performance issue with that ...
    SO i am trying to get the rows from ADF Iterator once we fetch from DB.
    Is it possible to do that ?
    Do we have any way to set the pointer to the VO/Iterator like setFirst() and after that setMaxResult to retrun the rows between first and maxresult..
    Thanks

    If this is for pagination, then af:table offers pagination by design when you set accessmode=RangePaging or RangePagingIncremental in VO. Paginated queries are fired when scroll down in the table. Explore this option before you try out any custom solution
    To answer the question,
    Note: same logic i have implpemented ADF with EJB ..In EJB Query class we have setFirst(int) and setMaxResult(int) methods...simply i did setFirst(30) and setMaxResult(10)..It worked fine...Theoretically speaking the same can be achieved by setting setRangeStart() on the viewobject(which in turn sets to the default rowset) and by setting max fetch size on VO + accessmode=RangePaging. However when you use table with ADF binding, these will be overridden by the binding layer. If you are not using ADF binding, then the above is same as what you did for JPA entity. Other option is, you build expert mode VO with rownum for this special case, which will work if you dont need to set accessmode=RangePaging for VO.

  • How to get selected row from table(FacesCtrlHierBinding ).

    I'am trying to get selected row data from table:
    FacesCtrlHierBinding rowBinding = (FacesCtrlHierBinding) tab.getSelectedRow();
    Row rw = rowBinding.getRow();
    But import for oracle.adfinternal.view.faces.model.binding.FacesCtrlHierBinding cannot be found from my JDev 11.
    What is correct package for FacesCtrlHierBinding?

    Hi, another problem.
    I fill table with data manualy from source:
    <af:table var="row" value="#{getCompanyData.com}"
    rowSelection="single" columnSelection="single"
    editingMode="clickToEdit"
    binding="#{getCompanyData.tab}"
    selectionListener="#{getCompanyData.GetSelectedCompany}">
    <af:column sortable="false" headerText="col1">
    <af:outputText value="#{row.id}"/>
    </af:column>
    <af:column sortable="false" headerText="col2">
    <af:outputText value="#{row.name}"/>
    </af:column>
    <af:column sortable="false" headerText="col3">
    <af:outputText value="#{row.phone}"/>
    </af:column>
    </af:table>
    and when I'am trying to use method to get selected row:
    RichTable table = this.getTab(); //get table bound to UI Table
    RowKeySet rowKeys = table.getSelectedRowKeys();
    Iterator selection = table.getSelectedRowKeys().iterator();
    while (selection.hasNext())
    Object key = selection.next();
    table.setRowKey(key);
    Object selCompany = table.getRowData();
    JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding) selCompany;
    row = rowData.getRow();
    I got an error:
    SEVERE: Server Exception during PPR, #1
    javax.el.ELException: java.lang.ClassCastException: data.COMPANY cannot be cast to oracle.jbo.uicli.binding.JUCtrlHierNodeBinding
    When I created tables by dragging data from date control, all worked fine.
    What could be a problem?

  • Cannot get all rows from cfProcResult

    We upgraded one of our servers (A) from CF 6 to 7.02. Another
    server (B) has CF 7.01.
    On server B (CF 7.01) the code works (below), all rows of
    each dataset are returned.
    Now on server A (CF 7.02) all of the resulting datasets have
    only the first record in them. If I add maxrows="-1" to each of the
    cfProcResult tags there is no change. If I change that to
    maxrows="100" then I can get the rows up to 100.
    Is this a bug or is there a different means to return all
    rows?

    It think its a bug. I got the same results under MX 7.0.2.
    The topic of maxrows recently came up on another thread. I
    did some searching and according to TechNote 18339 there was a
    change with maxrow
    "<cfquery maxrows=N> bug. ColdFusion MX (until ColdFusion
    MX 7.0.1 CHF2) didn't pass maxrows to the underlying driver
    (statement.setMaxRows())"
    Given the results you're getting, it sounds like CF is
    applying the maxrow to all of the resultsets, not just the one
    where maxrows was declared. I suspect cfstoredproc's usage of
    statement.setMaxRows() is incorrect. Thats just a guess though.
    Bottom line, I think you'll need handle it manually.
    Personally, I would recommend placing the row count logic in the
    stored procedure (if possible). The overall results will be more
    consistent and you won't have to worry about this kind of issue
    again.
    http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_18339
    http://livedocs.adobe.com/coldfusion/7/htmldocs/00000314.htm
    http://www.remotesynthesis.com/blog/index.cfm/2006/3/23/Maxrows-Issue-in-CFQuery

  • Problem getting correct data from MS Access after doing an Update

    Hi all,
    I have a problem getting correct data after doing an update. This is the scenario
    I am selecting some(Eg: All records where Column X = �7� ) records and update a column with a particular value (SET Column X = �c� ) in all these records by going through a while loop. In the while loop I add these records to a vector too, and pass it as the return value.
    After getting this return value I go through a for loop and get each record one by one from the DB and check if my previous update has actually happened. Since No errors were caught while updating DB, I assume all records are updated properly but my record set shows one after another as if it has not been updated. But if I open the DB it is actually updated.
    This does not happen to all records, always it shows like this
    1st record     Mode = �c�
    2nd record     Mode = �7�
    3st record     Mode = �c�
    4nd record     Mode = �7�
    9th record     Mode = �c�
    10th record     Mode = �7�
    I am relatively new to java and this is someone elses code that I have to modify,So I am not sure if there some thing wrong in the code too
    //Here is the method that gets records and call to update and add to vector
    public static Vector getCanceledWorkOrders() throws CSDDBException{
    //Variable declaration
      try {
        objDBConn = DBHandler.getCSDBCon();
        strSQL  = "SELECT bal bla WHERE [Detailed Mode])=?)";
        objStmt = objDBConn.prepareStatement(strSQL);   
        objStmt.setString(1, '7');
        objWOPRs = objStmt.executeQuery();
        while (objWOPRs.next()) {
         //Add elements to a vector by getting from result set
          //updating each record as PROCESSING_CANCELLED_WO(c)
          iRetVal = WorkOrderDetailingPolicy.updateRecordStatus(objPWODP.iWorkOrderNumber, objPWODP.strPersonInformed, EMSConstants.PROCESSING_CANCELLED_WO);
          if (iRetVal == -1) {
            throw new NewException("Updating failed");
      catch (Exception e) {
        vecWONumbers = null;
        throw new CSDDBException(e.getMessage());
      }finally{
        try {
          objWOPRs.close();
          objStmt.close();
          DBHandler.releaseCSDBCon(objDBConn);
        catch (Exception ex) {}
      //return vector
    //here is the code that actually updates the records
    public static int updateRecordStatus(int iWONumber, String strPerInformed , String strStatus) throws CSDDBException{
       PreparedStatement objStmt = null;
       Connection objDBConn  = null;
       String strSQL = null;
       int iRetVal = -1;
       try{
         objDBConn  = DBHandler.getCSDBCon();
         objDBConn.setAutoCommit(false);
         strSQL = "UPDATE Table SET [Detailed Mode] = ? WHERE bla bla";
         objStmt = objDBConn.prepareStatement(strSQL);
         objStmt.setString(1, strStatus);    
         objStmt.execute();
         objDBConn.commit();
         iRetVal = 1;
       }catch(Exception e){
         iRetVal = -1;
       }finally{
         try{
           objStmt.close();
           DBHandler.releaseCSDBCon(objDBConn);
         }catch(Exception ex){}
       return iRetVal;
    //Here is the code that call the records again
      public static WorkOrderDetailingPolicy getWorkOrders(int iWorkOrderNo) throws CSDDBException{
        Connection objDBConn = null;
        PreparedStatement objStmt = null;
        ResultSet objWOPRs = null;
        WorkOrderDetailingPolicy objPWODP = null;
        String strSQL = null;
        try {
          objDBConn = DBHandler.getCSDBCon();    
          strSQL = "SELECT * FROM [Work Order Detailing] WHERE [Work Order No] = ?";
          objStmt = objDBConn.prepareStatement(strSQL);
          objStmt.setInt(1, iWorkOrderNo);
           objWOPRs = objStmt.executeQuery();
          if (objWOPRs.next()) {
            objPWODP = new WorkOrderDetailingPolicy();
            objPWODP.iWorkOrderNumber = objWOPRs.getInt("Work Order No");
            //......Get Record values
        catch (Exception e) {
          objPWODP = null;
          throw new CSDDBException(e.getMessage());
        }finally{
          try {
            objWOPRs.close();
            objStmt.close();
            DBHandler.releaseCSDBCon(objDBConn);
          catch (Exception ex) {}
        return objPWODP;
      }

    Hello,
    Can you put an example of your problem online?
    Are you sure you're not having problems with case sensitive data?
    Thanks,
    Dimitri

  • How to get the rows from a table having some column has any letter

    Hi All,
    suppose i have a table having columns id(number), code(varchar).
    code has alphanumeric characters (ex. ABC123, 67B56 etc).
    some codes are only numbers (2344, 7898 etc).
    how can i get the rows which have alphabets in the code.
    ex:
    id code
    1 AB45
    2 456
    3 890
    4 67B7
    how can i write a query such that it should give me the ids 1 and 4 (as they have alphabets in code)
    thanks in advance to all

    Thanks to one and all.
    i am gettig my required output.
    But i have a doubt in the operator.
    If i add or remove '[]' in the operator, i am getting different ouputs.
    There is a count difference in the result of the operators used.
    REGEXP_LIKE(<column>,'[[:lower:]]')
    REGEXP_LIKE(<column>,'[[[:lower:]]]')
    REGEXP_LIKE(<column>,'[:lower:]')
    Can anybody please explain what is the difference in using '[]', in the operator?
    What is the correct syntax, whether i have to use two '[]'s or one '[]'.
    Also, can i use REGEXP_LIKE() in oracle 8i version.( I am unable to use the operator in 8i)?
    Any query to get the required output in 8i version?
    Thanks in advance to all.

  • How to get selected row from a non-bind ADF table

    Hi,
    I have an ADF table that is based on a collectionModel built programmatically. The collectionModel is this:
    model = new SortableModel(new ArrayList<ArrayList>());
    Hence, it is not a binding table. My question is how to get the selectedRows from a non-bind table.
    I am used to building binding ADF table and I know we can get it from voiterator.getCurrentRow, since the selectionListener is set to the binding....collectionModel.makeCurrent
    <af:table value="#{bindings.ItasLookupTypesVO1.collectionModel}"
    selectedRowKeys="#{bindings.ItasLookupTypesVO1.collectionModel.selectedRow}"
    selectionListener="#{bindings.ItasLookupTypesVO1.collectionModel.makeCurrent}"
    </af:table>
    I am thinking maybe I need to write my own selectionListener, but need more advice/ideas of what's the codes in the customer selection Listener to get it from my SortableModel.
    Please help.
    Thanks
    -Mina

    I'm not sure if this works in your case, but check out the selection listener I write in this blog http://wp.me/pcBZk-eu
    You should use the selection event and check the added set. This should give you access to the selected row.
    Timo

  • Get multiple rows from mysql query in NetBeans

    Hi, I am working on a project in NetBeans 6.I have a checkboxlist, and I have a variable in which I save the selected values of the checkboxlist.Now, I want to make a query that will get the rows of the rowset that have the same id as the selected values.for example, I have a checkboxlist that has the following values: Helen, Maria, Anna.The user checks the first two, so I have a variable String[] "checked" that has in it the data 1,2.Now, I have a rowset that has the following query:
    SELECT ALL person.age
    FROM person
    WHERE person.id=? or something like this.I want the parameters to have the values (1,2) so that the rowset has the results of the ages of the two first rows.How do I accomplish that?I am assuming that with one "?" it can't be done because I need multiple parameters. Will something like this work: WHERE person.id IN something,but what will something be?

    christomar wrote:
    I have a rowset that has the following query:
    SELECT ALL person.age
    FROM person
    WHERE person.id=? or something like this.I want the parameters to have the values (1,2) so that the rowset has the results of the ages of the two first rows.How do I accomplish that?Use a PreparedStatement. You probably first need to read the Sun JDBC Tutorial before you do anything.
    I am assuming that with one "?" it can't be done because I need multiple parameters. I've seen people use up to 76 parameters so yes it can be done, it will look like this:
    Will something like this work: WHERE person.id IN something,Yes, you can submit any SQL you want as long as your db supports it (all support ANSI i believe)
    but what will something be?something in that context would be a list/set of data, but you're getting ahead of yourself I think. do the tutorial and look at some code

  • Getting correct row based on date

    Hi,
    if i have the following records for an account:
    now i have a date of 4-1-2013 and I want the row where either 4-1-2013 falls withing the BeginDt and EndDt OR if it does not fall within the BeginDt and EndDt, i wann the EndDt = null row.  So i should only get one row back each time, in this case I
    would get the first row back.
    thanks

    Hi,
    You can use BETWEEN statement to find rows where the date is between your date columns and you can use OR to get the second row if it's not inside the interval.
    There are other solutions, I've implemented this one:
    DECLARE @MyTable TABLE (OrgRoleNumTxt VARCHAR(20), BeginDt DATETIME, EndDt DATETIME);
    DECLARE @SearchDate DATETIME;
    INSERT INTO @MyTable
    SELECT '07238', '2013-01-01 00:00:00', '2013-06-30 23:59:59.997'
    UNION
    SELECT '07238', '2015-03-05 00:00:00', NULL
    -- Scenario #1: Returns the first record (between dates)
    SET @SearchDate = '2013-04-01';
    SELECT TOP 1 * FROM @MyTable WHERE (@SearchDate BETWEEN BeginDt AND EndDt) OR EndDt IS NULL ORDER BY BeginDt ASC;
    -- Scenario #2 (same query): Returns the second record (end date is null)
    SET @SearchDate = '2014-01-01';
    SELECT TOP 1 * FROM @MyTable WHERE (@SearchDate BETWEEN BeginDt AND EndDt) OR EndDt IS NULL ORDER BY BeginDt ASC;
    Hope this helps,
    Please use Mark as Answer if my post solved your problem and use Vote As Helpful if a post was useful.
    Pedro Martins
    Portugal
    https://www.linkedin.com/in/rechousa

  • How to get two rows from this data?

    SQL Gurus,
    I need to summarize the following data into two rows (two rows based on the example data below but it can be any number of rows if there are more breaks in continuos numbers)
    DETAIL_ID     FM_SERIAL_NUMBER     TO_SERIAL_NUMBER
    63009     11     11
    63009     12     12
    63009     13     13
    63009     14     14
    63009     15     15
    63009     16     16
    63009     17     17
    63009     18     18
    63009     19     19
    63009     20     20
    63009     228     228
    I need to get two rows, one showing 11-20 (that's because there's a conituity between 11 to 20)
    and the other row showing 228 - 228.
    Any help is appreciated
    Regards,
    Srini

    the example i gave had some issues.
    Here is an updated code.
    Provided your detail_id,f_serial_no,t_serial_no are numbers.
    Thanks to the example provided by Karthick_Arp      
    link:genterating one order
    WITH t AS
      (SELECT 63009 a,
        level b    ,
        level c
         FROM dual CONNECT BY level < 10
    UNION ALL
       SELECT 63009 , 228,228 FROM dual
    UNION ALL
    SELECT 63009 , 229,229 FROM dual
    UNION ALL
       SELECT 63009 , 238,238 FROM dual
    UNION ALL
       SELECT 63009,239,239 FROM dual
    UNION ALL
       SELECT 630010,223,223 FROM dual
    UNION ALL
       SELECT 630010,224,224 FROM dual
       union all
    SELECT 63009,232,232 FROM dual
      , t1 as (
      select a, b, c, decode(b-nvl(lag(b) over (partition by a order by b),1),1,0,b) d from t)
      ,t2 as (
      select a, b, c,d
         from (select row_number() over(order by b) rno, a,b,c,d
            from t1) t
        model
        return updated rows
        dimension by (rno)
        measures (a, b, c,d)
        rules update
          d[any] = case when d[cv()] = 0 then nvl(d[cv()-1],0) else d[cv()] end
        select a,min(b),max(b) from t2
        group by a,doutput
    63009     1     9
    630010     223     224
    63009     232     232
    63009     228     229
    63009     238     239
    Alvinder
    Edited by: alvinder on Feb 20, 2009 9:28 AM

  • Get selected row from grid

    Hi
    I use JDev 11.1 with ADF, i have grid, i need to get selected row of grid when i press buttom, how can i do that?
    Thanks

    Hi,
    You have a table in your page that is based on a viewObject iterator and you need to get the selected row in your backing bean when you click on a button.
    Did I get this right?
    If so then you need to add an actionListener on this button that executes a method in the backing bean.
    the button code:
    <af:commandButton text="commandButton 1" id="cb1"
                                        actionListener="#{myBean.buttonActionListener}"/>In this method you need to add code like this:
      public void buttonActionListener(ActionEvent actionEvent) {
        BindingContext bindingctx=BindingContext.getCurrent();
        DCBindingContainer bindings=(DCBindingContainer)bindingctx;
        DCIteratorBinding iter= bindings.findIteratorBinding("iteratorName");
        Row currentRow=iter.getCurrentRow();
      }If this is not what you need give some more details.
    Gabriel

  • Get exact row from database table

    This is part of my source code that displays one row from getQuest recordset. Always first.
    <body>
    <p><?php echo $row_getQuest['content']; ?></p>
    <p>: <?php echo $row_getQuest['prom1']; ?></p>
    <p><?php echo $row_getQuest['prom2']; ?></p>
    <?php echo $row_getQuest['dos1']; ?>(); <?php echo $row_getQuest['dos2']; ?> (); <?php echo $row_getQuest['dos3']; ?> (); <?php echo $row_getQuest['dos4']; ?>(); <?php echo $row_getQuest['dos5']; ?> (); <?php echo $row_getQuest['dos6']; ?> (); <?php echo $row_getQuest['dos7']; ?> ().
    </body>
    Can i change it so, that on this page it always displayed row with exact position in the table - for example second or 15th - independently of row contents and rows deletition, moving or changing in table?

    But if I add 5 rows to table, then delete all of them and add 5 again - auto incremented id will 6 for first in table and 10 for last. If i delete all and add 5 again it will be 11...15 and so on. As I said - I cannot rely on row contens - because I'm planning to delete and add data from that table frequently. Or other solution could be to allways keep id from 1 to [amount of rows]. I do not know how this is done.
    Or am I wrong about id?

  • Programmatically get result rows from query component?

    I am using a af:query for searching values without the table. When i search, is there any way in which i can get the search results Programmatically?
    Thanks
    Ajay

    Intercept the query invokation using your own queryListener method, and then get the Iterator from the VO. http://jobinesh.blogspot.com/2011/03/retrieving-viewcriteria-from-custom.html

Maybe you are looking for

  • How can I find out the name of an artist in the download library?

    Yesterday my friend configured his iPod nano. At the end of the setup, a library of some 30 songs was downloaded to his iPod. He told me he loved one of the songs called Sons and Daughters, but the album/artist displayed as Anonymous. It's a moving a

  • Making a Video a TV Show

    Hi! Ok, so I uploaded some videos into my itunes and i want to classify them as a TV Show. However when I do that, it doesn't let me input its Show Name, or Season or anything besides the title. Even under artist and album I put the info and it doesn

  • Fonts not smooth

    Dear all, Is there a way to enhance the print-out fonts of CF Report Builder? On the screen it is quite smooth (FlashPaper), but when I do the printing (to printer or PDF) all characters are not that smooth. I use the same font (Arial) and font size

  • IWEB 08 menu disappears

    I installed OS 10.5.1 and the new Ilife 08. Building a website with iweb if I browse it with explorer (win XP) the menu with the link does not appear (I tried with different computers). No problems with Safari or Firefox. Anyone has an idea?

  • Yosemite re-installation not possible!!!

    My Mac crashed because of a driver installation. My boot HD is not starting anymore. It just shows a grey crossed circle after 1 minute. I tried to re-install it via recovery partition. That doesn't work. The installation got stuck. I thought about a