How NOT to restrict no of rows from two tables

I have two identical tables Invoice and Payment. The only difference is Invoice_id,Invoice_Amt and Payment_id,Payment_Amt columns that shows different ids and amounts. The bank_ids, names, account_types are same. Invoice table has 3 rows and Payment has 2. Simply meaning that there were 3 invoices generated but the bank received 2 payments. I want to show Invoice_Amt and Payment_Amt using sql query. But its giving me total 6 rows. Whereas, I want 3 from Invoice and 2 rows from Payment table to show side-by-side.
CREATE TABLE invoice
( invoice_id NUMBER
bank_id NUMBER,
bank_name VARCHAR2(256),
invoice_amount NUMBER);
----Invoice table has 3 rows showing 3 Invoice Amts
CREATE TABLE payment
( payment_id NUMBER
bank_id NUMBER,
bank_name VARCHAR2(256),
payment_amount NUMBER);
----Payment table has 2 rows showing 2 Payments
After executing this sql statement below, I get 6 rows:
select inv.invoice_amount,pymt.payment_amount from invoice inv,payment pymt where inv.bank_id=pymt.bank_id;
How can I show 3 rows for Invoice and 2 for Payment..?
Thank you.

Hi,
So you want
the 1st invoice to appear side-by-side with the 1st payment,
the 2nd invoice to appear side-by-side with the 2nd payment,
the nth invoice to appear side-by-side with the nth payment.
But, if there are an uneqaul numner of payments and invoices, all the payments and all the invoices must still be shown, alone on a row if necessary.
That sounds like a job for FULL OUTER JOIN.
Use the analytic ROW_NUMBER fucntion to determine which is the 1st, 2nd, ..., nth row in each table, for each bank.
WITH     invoice_plus_r_num     AS
     SELECT     bank_id, bank_name
     ,      invoice_amount
     ,     ROW_NUMBER () OVER ( PARTITION BY  bank_id, bank_name
                               ORDER BY          invoice_id
                       )         AS r_num
     FROM    invoice
,     payment_plus_r_num     AS
     SELECT     bank_id, bank_name
     ,      payment_amount
     ,     ROW_NUMBER () OVER ( PARTITION BY  bank_id, bank_name
                               ORDER BY          payment_id
                       )         AS r_num
     FROM    payment
SELECT       NVL (i.bank_id,   p.bank_id)          AS bank_id
,       NVL (i.bank_name, p.bank_name)     AS bank_name
,       i.invoice_amount
,       p.payment_amount
FROM          invoice_plus_r_num     i
FULL OUTER JOIN     payment_plus_r_num     p  ON   i.bank_id     = p.bank_id
                                    AND     i.bank_name     = p.bank_name
                            AND     i.r_num          = p.r_num
ORDER BY  bank_id     -- you can use column aliases here
,       bank_name
,       NVL (i.r_num, p.r_num)
;You mentioned something about accounts, but didn't include that in the CREATE TABLE statements. You'll probably want to add that wherever I used bank_id and bank_name, above.
Are invoce and payment actually views, rather than tables? If not, you should have a separate bank table, and only include the bank_id in the other tables.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using.
Edited by: Frank Kulash on Feb 3, 2011 12:32 PM

Similar Messages

  • How to compare two rows from two table with different data

    how to compare two rows from two table with different data
    e.g.
    Table 1
    ID   DESC
    1     aaa
    2     bbb
    3     ccc
    Table 2
    ID   DESC
    1     aaa
    2     xxx
    3     ccc
    Result
    2

    Create
    table tab1(ID
    int ,DE char(10))
    Create
    table tab2(ID
    int ,DE char(10))
    Insert
    into tab1 Values
    (1,'aaa')
    Insert
    into tab1  Values
    (2,'bbb')
    Insert
    into tab1 Values(3,'ccc')
    Insert
    into tab1 Values(4,'dfe')
    Insert
    into tab2 Values
    (1,'aaa')
    Insert
    into tab2  Values
    (2,'xx')
    Insert
    into tab2 Values(3,'ccc')
    Insert
    into tab2 Values(6,'wdr')
    SELECT 
    tab1.ID,tab2.ID
    As T2 from tab1
    FULL
    join tab2 on tab1.ID
    = tab2.ID  
    WHERE
    BINARY_CHECKSUM(tab1.ID,tab1.DE)
    <> BINARY_CHECKSUM(tab2.ID,tab2.DE)
    OR tab1.ID
    IS NULL
    OR 
    tab2.ID IS
    NULL
    ID column considered as a primary Key
    Apart from different record,Above query populate missing record in both tables.
    Result Set
    ID ID 
    2  2
    4 NULL
    NULL 6
    ganeshk

  • Select unique rows from two tables...

    Hi,
    I have two tables, replies1 and replies2.
    SQL> desc replies
    Name Null? Type
    URN VARCHAR2(36)
    ADDRESS VARCHAR2(18)
    FILESIZE NUMBER
    AS_NUM VARCHAR2(6)
    SQL> desc replies2
    Name Null? Type
    URN VARCHAR2(36)
    ADDRESS VARCHAR2(18)
    AS_NUM VARCHAR2(6)
    Both of the tables have no primary keys, but I have indixes on (urn, addrss) combination on both....
    I am trying to select the unique rows with (urn, address) from replies2, and then find the matching size from replies...
    I am using the following query:
    select distinct replies2.urn, replies2.address, replies.filesize from replies2, replies where replies2.AS_NUM like 'XYZ' and replies.urn = replies2.urn;
    I cannot figure out why it won't work. the way I understand it is that, distinct will give all distinct combination of all column names that follow, which is what I want...
    I know it is wrong, because the query:
    select count(*) from replies2 where AS_NUM like 'XYZ' returns less number of rows than the above query.
    Any help would be greatly appreciated.
    Thank you
    Oz.

    Thanks a lot Mohan for your reply.
    urn is not a unique key. Several rows could have the same (urn, address) pair in both tables. What I want is retrieve all (urn, address) rows from one table, and find the size from the other table to make a (urn, address, size). I want all unique combinations of (urn, address) to appear in the output.
    AS_NUM is an empty column in replies... It would've been a lot easier if it wasn't, since then I'll just say: select distinct urn, address, filesize from replies where AS_NUM like 'XYZ';
    I will try your query though and let u know how it goes. It takes quite a while to run since my tables are huge.

  • How can I get the selected rows from two ALV grids at the same time?

    I have a program that uses two ALV grids in one dialog screen. I'm using the OO ALV model (SALV* classes).
    The user can select any number of rows from each grid. Then, when a toolbar pushbutton is pressed, I'd have to retrieve the selected rows from both grids and start some processing with these rows.
    It is no problem to assign event handlers to both grids, and use the CL_SALV_TABLE->GET_SELECTIONS and CL_SALV_SELECTIONS->GET_SELECTED_ROWS methods to find out which rows were marked by the user. Trouble is, this only works when I raise an event in each grid separately, for instance via an own function that I added to the grid's toolbar. So, I can only see the selected rows of the same grid where such an event was raised.
    If I try to do this in the PBO of the dialog screen (that contains the two grids), the result of CL_SALV_SELECTIONS->GET_SELECTED_ROWS will be empty, as the program does not recognize the marked entries in the grids. Also, an event for grid1 does not see the selected rows from grid2 either.
    As it is right now, I can have an own button in both grid's toolbar, select the rows, click on the extra button in each grid (this will tell me what entries were selected per grid). Then, I'd have to click on a third button (the one in the dialog screen's toolbar), and process the selected rows from both grids.
    How can I select the rows, then click on just one button, and process the marked entries from both grids?
    Is it somehow possible to raise an event belonging to each grid programmatically, so that then the corresponding CL_SALV_SELECTIONS->GET_SELECTED_ROWS will work?
    Thanks.

    Hello Tamas ,
    If I try to do this in the PBO of the dialog screen (that contains the two grids), the result of CL_SALV_SELECTIONS->GET_SELECTED_ROWS will be empty, as the program does not recognize the marked entries in the grids. Also, an event for grid1 does not see the selected rows from grid2 either.--->
    is it possible to  have a check box in each grid  & get the selected lines in PAI of the screen ?
    regards
    prabhu

  • Delete operation is not working to delete selected row from ADF table

    Hi All,
    We are working on jdev 11.1.1.5.3. We have one ADF table as shown below. My requirement is to delete a selected row from table, but it is deleting the first row only.
    <af:table value="#{bindings.EventCalendarVO.collectionModel}" var="row"
    rows="#{bindings.EventCalendarVO.rangeSize}"
    emptyText="#{bindings.EventCalendarVO.viewable ? applcoreBundle.TABLE_EMPTY_TEXT_NO_ROWS_YET : applcoreBundle.TABLE_EMPTY_TEXT_ACCESS_DENIED}"
    fetchSize="#{bindings.EventCalendarVO.rangeSize}"
    rowBandingInterval="0"
    selectedRowKeys="#{bindings.EventCalendarVO.collectionModel.selectedRow}"
    selectionListener="#{bindings.EventCalendarVO.collectionModel.makeCurrent}"
    rowSelection="single" id="t2" partialTriggers="::ctb1 ::ctb3"
    >
    To perform delete operation i have one delete button.
    <af:commandToolbarButton
    text="Delete"
    disabled="#{!bindings.Delete.enabled}"
    id="ctb3" accessKey="d"
    actionListener="#{AddNewEventBean. *deleteCurrentRow* }"/>
    As normal delete operation is not working i am using programatic approach from bean method. This approach works with jdev 11.1.1.5.0 but fails on ver 11.1.1.5.3
    public void deleteCurrentRow (ActionEvent actionEvent) *{*               DCBindingContainer bindings =
    (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding dcItteratorBindings =
    bindings.findIteratorBinding("EventCalendarVOIterator");
    // Get an object representing the table and what may be selected within it
    ViewObject eventCalVO = dcItteratorBindings.getViewObject();
    // Remove selected row
    eventCalVO.removeCurrentRow();
    it is removing first row from table still. Main problem is not giving the selected row as current row. Any one point out where is the mistake?
    We have tried the below code as well in deleteCurrentRow() method
    RowKeySet rowKeySet = (RowKeySet)this.getT1().getSelectedRowKeys();
    CollectionModel cm = (CollectionModel)this.getT1().ggetValue();
    for (Object facesTreeRowKey : rowKeySet) {
    cm.setRowKey(facesTreeRowKey);
    JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)cm.getRowData();
    rowData.getRow().remove();
    The same behavior still.
    Thanks in advance.
    Rechin
    Edited by: 900997 on Mar 7, 2012 3:56 AM
    Edited by: 900997 on Mar 7, 2012 4:01 AM
    Edited by: 900997 on Mar 7, 2012 4:03 AM

    JDev 11.1.1.5.3 sounds like you are using oracle apps as this not a normal jdev version.
    as it works in 11.1.1.5.0 you probably hit a bug which you should file with support.oracle.com...
    Somehow you get the first row instead of the current row (i guess). You should debug your code and make sure you get the current selected row in your bean code and not the first row.
    This might be a problem with the bean scope too. Do you have the button (or table) inside a region? Wich scope does the bean have?
    Anyway you can try to remove the iterator row you get
    public void deleteCurrentRow (ActionEvent actionEvent) { DCBindingContainer bindings =
    (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding dcItteratorBindings =
    bindings.findIteratorBinding("EventCalendarVOIterator");
    dcItteratorBindings.removeCurrentRow();Timo

  • How to return mismatched rows from two tables?

    I have created two tables in the same database as below which gives the row
    count of tables across all databases before and after an DB restore
    operation.
    create table before_restore(db_name varchar(100),table_name
    varchar(1000),row_count int) insert into before_restore exec sp_msforeachdb 'USE
    [?]; select ''?'' as database_name,o.name,max(i.rowcnt ) From [?].sys.objects o
    inner join [?].sys.sysindexes i on o.object_id=i.id where o.type=''U'' group by
    o.name'
    create table after_restore(db_name varchar(100),table_name
    varchar(1000),row_count int) insert into after_restore exec sp_msforeachdb 'USE
    [?]; select ''?'' as database_name,o.name,max(i.rowcnt ) From [?].sys.objects o
    inner join [?].sys.sysindexes i on o.object_id=i.id where o.type=''U'' group by
    o.name'
    I want to compare these two tables and it should only return me rows that
    have changed after the restore operation is complete.
    Eg:
    Table xyz has rowcount of 100 before restore and the restore was not proper
    and after restore count is 50. So it should return me the result set as
    below;
    Db_name    Table_Name  row_count_before_restore    row_count_after_restore
    abc                   xyz                       100                              
       50
    Thanks!!!

    Something like below perhaps? Btw, I recommend using catalog view and dynamic management views instead of the old system tables (now called compatibility views)...
    SELECT
    COALESCE(a.db_name, b.db_name) AS db_name
    ,COALESCE(a.table_name, b.table_name) AS table_name
    ,a.row_count AS row_count_before_restore
    ,b.row_count AS row_count_after_restore
    FROM before_restore AS b FULL OUTER JOIN after_restore AS a ON b.db_name = a.db_name AND b.table_name = a.table_name
    WHERE b.row_count <> a.row_count OR b.db_name IS NULL OR a.db_name IS NULL
    Tibor Karaszi, SQL Server MVP |
    web | blog

  • How can we restrict the f4 help from check table in the pop up form.

    Hi,
    I am trying to control the F4 help values from check table coming in the form of pop up.

    When a user uses SM30 to add an entry into table, you often need to add more checks. If you were to add code inside, there is a big chance that it would be overwritten.
    The solution: go to table maintenance generator ( se56) => Enviroment => add event.
    [To add event in table main.|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/8129f164-0a01-0010-2a8e-8765287250fc]

  • How to select x numbered row from two tables

    Hi,
    I have one performance problem...
    Here is sample scenario...
    TableA
    A1 A2 A3
    a1     a12     a13
    a2     a22     a23
    a3     a32     a33
    TableB
    B1     B2     B3
    b1     b12     b13
    b2     b22     b23
    I want result like
    A1     B1     A2     B2
    a1     b1     a12     b12
    a2     b2     a22     b22
    I have written it like
    select
    A1,
    B1,
    A2,
    B2
    from
    (select A1, A2, rownum rnA from TableA) a,
    (select B1, B2, rownum rnB from TableB) b
    where rnA = rnB
    but suppose TableA has 2500000 rows and
    TableB has 500 rows then for 500 rows I have to
    wait for all 2500000 rows scanning.
    Is there any smart solution..?
    I have created indexes for on columns A1, (A1,A2,A3), B1, (B1,B2,B3).
    Curious:)
    Rushang Kansara
    Message was edited by:
    Rushang Kansara

    Here is explain plan
    SELECT STATEMENT, GOAL = FIRST_ROWS               Cost=5     Cardinality=67     Bytes=3618
    HASH JOIN               Cost=5     Cardinality=67     Bytes=3618
    VIEW     Object owner=SFMFG          Cost=2     Cardinality=82     Bytes=2214
    COUNT                         
    TABLE ACCESS FULL     Object owner=SFMFG     Object name=TABLEA     Cost=2     Cardinality=82     Bytes=1148
    VIEW     Object owner=SFMFG          Cost=2     Cardinality=82     Bytes=2214
    COUNT                         
    TABLE ACCESS FULL     Object owner=SFMFG     Object name=TABLEB     Cost=2     Cardinality=82     Bytes=1148
    New to sql tunning Here why cardinality goes to 67 and cost to 5???
    Thank you for your time.. :)

  • Distinct rows from two tables linked by a third one

    Hi,
    I need to write an SQL sentence to bring a group of DISTINCT rows, each row in a form of: A.X, A.Y, C.IDBOLETA. Tables A and C are linked through the table C, as follow:
    Table A: INDUSTRIAGEO
    NIT VARCHAR2(20) NOT NULL,
    CORRELAIGEO NUMERIC(2) NOT NULL,
    NOMBREAGENCIA VARCHAR2(255) NOT NULL,
    DIRECCION VARCHAR2(255),
    X NUMERIC(12,8) NOT NULL,
    Y NUMERIC(12,8) NOT NULL,
    CONSTRAINT PKGEOINDUST PRIMARY KEY(NIT, CORRELAIGEO),
    CONSTRAINT FKGEOINDUST FOREIGN KEY(NIT) REFERENCES INDUSTRIA(NIT)
    Table B: ANALISIS
    IDANALISIS NUMERIC(12) NOT NULL,
    NIT VARCHAR2(20) NOT NULL,
    CORRELAIGEO NUMERIC(2) NOT NULL,
    FECHA DATE NOT NULL,
    IDINSPECTOR NUMERIC(4) NOT NULL,
    CONSTRAINT PKANALISIS PRIMARY KEY(IDANALISIS),
    CONSTRAINT FKANALGEOI FOREIGN KEY(NIT, CORRELAIGEO) REFERENCES INDUSTRIAGEO(NIT, CORRELAIGEO),
    CONSTRAINT FKANALINSP FOREIGN KEY(IDINSPECTOR) REFERENCES INSPECTOR(IDINSPECTOR)
    Table C: ANALISISBOLETA
    IDANALISIS NUMERIC(12) NOT NULL,
    CORRELAANALISIS NUMERIC(2) NOT NULL,
    IDBOLETA NUMERIC(12) NOT NULL,
    IDCATEGORIAINDUSTRIA NUMERIC(3) NOT NULL,
    CONSTRAINT PKANALBOLE PRIMARY KEY (IDANALISIS, CORRELAANALISIS),
    CONSTRAINT UKANALBOLE UNIQUE (IDBOLETA),
    CONSTRAINT FKANALBOLE FOREIGN KEY(IDANALISIS) REFERENCES COPS.ANALISIS(IDANALISIS),
    CONSTRAINT FKANALCATI FOREIGN KEY(IDCATEGORIAINDUSTRIA) REFERENCES COPS.CATEGORIAINDUSTRIA(IDCATEGORIAINDUSTRIA)
    Thanks for your help!!!
    Mario

    Perhaps
    select distinct a.x,a.y,c.idboleta
      from industriaego a,
           cops.analisis b,
           analisisboleta c
    where a.nit = b.nit
       and a.correlaigeo = b.correlaigeo
       and b.idanalisis = c.idanalisisRegards
    Etbin
    Edited by: Etbin on 4.5.2010 21:42
    the copy/paste elf did it again: b.correlaigeo instead of b.a.correlaigeo (as in the OP's comment below)

  • How to return the same SUM value from two tables

    Hello,
    I have the following data:
    SQL> SELECT * FROM t1;
         T1_ID   T1_VALUE
             1        500
             1        500
    SQL> SELECT * FROM t2;
         T2_ID   T2_VALUE
             1       1000
    SQL> SELECT t1_id, SUM(t1_value), SUM(t2_value)
      2    FROM t1, t2
      3   WHERE t1_id = t2_id
      4   GROUP BY t1_id;
         T1_ID SUM(T1_VALUE) SUM(T2_VALUE)
             1          1000          2000How is it possible that SUM(T2_VALUE) returns also 1000.
    Thank you

    Here's one way:
    with t1 as (select 1 t1_id, 500 t1_value from dual union all
                select 1 t1_id, 500 t1_value from dual),
         t2 as (select 1 t2_id, 1000 t2_value from dual)
    select t3.t3_id, t3.t3_sum, t4.t4_sum
    from   (select t1_id t3_id, sum(t1_value) t3_sum from t1
            group by t1_id) t3,
           (select t2_id t4_id, sum(t2_value) t4_sum from t2
            group by t2_id) t4
    where  t3.t3_id = t4.t4_id

  • How can i get all the records from three tables(not common records)

    Hi
    I have four base tables at R/3-Side. And i need to extract them from R/3-Side.
    And i dont have any standard extractor for these tables .
    If i create a 'View' on top of these tables. Then it will give only commom records among the three tables.
    But i want all the records from three base tables (not only common).
    So how can i get the all records from three tables. please let me know
    kumar

    You can create separate 3 datasources for three tables and extract data to BW. There you can implement business login to build relation between this data.

  • How to return the entire row from a table

    Hi guys,
    Tabl A
    FirstName varchar2(10),
    Age Number,
    Add varchar2(100),
    Table B
    Filedname varchar2(200), -- contains all the fields of table A
    Datatype varchar2(100), -- Contains the datatypes of the filedname
    Length Number -- contains the length of the fileds
    Now how can i return the entire row from table A with the datatype and its length.
    Any help would be appreciated ?
    Here is the query I wrote but it how to take the datatype and its length..
    create or replace procedure disp_table_data
    as
    type r_cursor is REF CURSOR;
    c_A r_cursor;
    er A%rowtype;
    begin
    open c_A for select * from A;
    loop
    fetch c_A into er;
    exit when c_A%notfound;
    dbms_output.put_line(er.FirstName||'--'||er.Age);
    end loop;
    close c_A;
    END;
    /

    Guys,
    I want column value from table A and its corresponding data_type and length from table B. I think I cant do it through joins.
    Any idea would be appreciated ?.
    Example ..
    Tabl A
    FirstName varchar2(10),
    Age Number,
    Add varchar2(100)
    insert into A values('John',24,'Boston');
    Table B
    Filedname varchar2(200), -- contains all the fields of table A
    Datatype varchar2(100), -- Contains the datatypes of the filedname
    Length Number -- contains the length of the fileds
    insert into B values('FirstName','varchar2',10); -- this is coming from table A.
    Output should be like this...
    John,Varchar2,10
    Here (John is the FirstName - coming from table A, Varchar2 is a Datatype and 10 is the Length which are coming from table B ). Only column values are coming from table A , corresponding datatype and length are coming from B.
    Any idea would be appreciated ?
    Thanks.

  • How to list all the rows from the table VBAK

    Friends ,
    How to list all the rows from the table VBAK.select query and the output list is appreciated.

    Hi,
    IF you want to select all the rows for VBAK-
    Write-
    Data:itab type table of VBAK,
           wa like line of itab.
    SELECT * FROM VBAK into table itab.
    Itab is the internal table with type VBAK.
    Loop at itab into wa.
    Write: wa-field1,
    endloop.

  • How to delete rows from multiple tables when pressing button

    Hi, I'm wondering how do I delete a row from two different tables at the same time when I press the Delete button. Both tables have GROUP_ID as their primary key.

    Nevermind! I realized that I had "reset" before my process to delete from the 2nd table.

  • How To Access PAGE ITEM (single row) from HTML source

    Hi Guys,
    I have a page Item that return a string.
    I would like to show this string
    How To Access PAGE ITEM (single row) from HTML source?
    My desire final output is
    <marquee>:P1_PAGE_ITEM</marquee>
    Can please help me
    Thanks

    Hi,
    You can refer the page items in your page header as &itemname. For example, if I have page item P15_TEST, I will add the following in header:
    <marquee>
       &P15_TEST.
    </marquee>But make sure that you have a process before header to populate the value in your page item. Otherwise, there will be a null scrolling (which you can't see!) :)
    Regards,
    Zahid

Maybe you are looking for