Issues while joining two tables as the joining column has duplicate values - Please help!

Hi,
I have a table A -which has few columns including a Amount column - I am joining this table A to Table B. The joining column in B has duplicates.  So, the number of records are getting more after the joining. As per the requirment when I create a table
after joining the tables and count the salary clumn, there is a difference in the counting. How can I solve this? Can you please help me?
Here is the DDL and sample values
create table #student (sid int, name varchar(10),salary int)
create table [#address] (sid int, city varchar(10),grade char(1),lineneumber int)
insert into #student values (1,'sachin',8000)
insert into #student values (2,'Dhoni',2000)
insert into #student values (3,'Ganguly',7000)
insert into #student values (4,'Kohli',1000)
insert into [#address] values(1,'mumbai','A',1)
insert into [#address] values(1,'mumbai','B',2)
insert into [#address] values(1,'mumbai','C',3)
insert into [#address] values(1,'mumbai','D',4)
insert into [#address] values(2,'JARKHAND','D',3)
insert into [#address] values(2,'JARKHAND','D',4)
SELECT S.SID,NAME,salary,CITY ,grade,linenumber
into #FINAL
FROM #STUDENT S
LEFT JOIN #ADDRESS A
ON S.SID=A.SID
SELECT SUM(salary) FROM #FINAL
--44000
Final result should be 18000 , but it is coming as 44000. can you please help me to get the correct result - what do i do in the joining?
In my real project, i have 5 tables joining, each table have more than 30 columns and few joining tables joining column have duplicates. I have simplified the issue so that i can ask the question clearly. So,while answering, please consider that also in mind.
thanks in advance for your help!

SELECT S.SID,NAME,salary,CITY 
into #FINAL
FROM #STUDENT S
LEFT JOIN (SELECT DISTINCT sid,city
FROM #Address) A
ON S.SID=A.SIDthis will do a join on student table and city table with unique sid and city name so adddress selection will be sid city1 mumbai2 jarkand

Similar Messages

  • How do I join two tables in the same database and load the result into a destination table in a SSIS package

    Hi,
    I have a query that joins two tables in the same database, the result needs to be loaded in a destination DB table.  How do I do this in SSIS package?
    thank you !
    Thank You Warmest Fanny Pied

    Please take a look at these links related to your query.
    http://stackoverflow.com/questions/5145637/querying-data-by-joining-two-tables-in-two-database-on-different-servers
    http://stackoverflow.com/questions/7037228/joining-two-tables-together-in-one-database

  • Need help to join two tables using three joins, one of which is a (between) date range.

    I am trying to develop a query in MS Access 2010 to join two tables using three joins, one of which is a (between) date range. The tables are contained in Access. The reason
    the tables are contained in access because they are imported from different ODBC warehouses and the data is formatted for uniformity. I believe this cannot be developed using MS Visual Query Designer. I think writing a query in SQL would be suiting this project.
    ABCPART links to XYZPART. ABCSERIAL links to XYZSERIAL. ABCDATE links to (between) XYZDATE1 and ZYZDATE2.
    [ABCTABLE]
    ABCORDER
    ABCPART
    ABCSERIAL
    ABCDATE
    [ZYXTABLE]
    XYZORDER
    XYZPART
    XYZSERIAL
    XYZDATE1
    XYZDATE2

    Thank you for the looking at the post. The actual table names are rather ambiguous. I renamed them so it would make more sense. I will explain more and give the actual names. What I do not have is the actual data in the table. That is something I don't have
    on this computer. There are no "Null" fields in either of the tables. 
    This table has many orders (MSORDER) that need to match one order (GLORDER) in GLORDR. This is based on MSPART joined to GLPART, MSSERIAL joined to GLSERIAL, and MSOPNDATE joined if it falls between GLSTARTDATE and GLENDDATE.
    [MSORDR]
    MSORDER
    MSPART
    MSSERIAL
    MSOPNDATE
    11111111
    4444444
    55555
    2/4/2015
    22222222
    6666666
    11111
    1/6/2015
    33333333
    6666666
    11111
    3/5/2015
    This table has one order for every part number and every serial number.
    [GLORDR]
    GLORDER
    GLPART
    GLSERIAL
    GLSTARTDATE
    GLENDDATE
    ABC11111
    444444
    55555
    1/2/2015
    4/4/2015
    ABC22222
    666666
    11111
    1/5/2015
    4/10/2015
    AAA11111
    555555
    22222
    3/2/2015
    4/10/2015
    Post Query table
    GLORDER
    MSORDER
    GLSTARTDATE
    GLENDDATE
    MSOPNDATE
    ABC11111
    11111111
    1/2/2015
    4/4/2015
    2/4/2015
    ABC22222
    22222222
    1/5/2015
    4/10/2015
    1/6/2015
    ABC22222
    33333333
    1/5/2015
    4/10/2015
    3/5/2015
    This is the SQL minus the between date join.
    SELECT GLORDR.GLORDER, MSORDR.MSORDER, GLORDR.GLSTARTDATE, GLORDR.GLENDDATE, MSORDR.MSOPNDATE
    FROM GLORDR INNER JOIN MSORDR ON (GLORDR.GLSERIAL = MSORDR.MSSERIAL) AND (GLORDR.GLPART = MSORDR.MSPART);

  • My iphone 3g is not charging and the middle button has stoped working please help. My phone has no power now

    My iphone 3g is not charging and the middle button has stoped working please help. My phone has no power now an i need help

    For a broken home button you can find your options here http://www.apple.com/support/service/

  • Merge Two Tables with the same columns but different data

    I have a table that has the following columns:
    Current Table Definition
    commonname
    family
    genus
    species
    subspecies
    code
    I have a number of entries that don’t fit the current table definition – that is that they only have a common name or description and a code. These records don’t actually represent a species but are needed for data entry because they represent an object that may be encountered in the study (Bare Ground – which isn’t a species but would need to be recorded if encountered). So I would really like 2 tables:
    Table 1 Miscellaneous
    name
    code
    Table 2 Plant Species
    commonname
    family
    genus
    species
    subspecies
    code
    I would like two tables so I can enforce certain constraints on my species table like requiring that the family, genus, species, subspecies combination is unique. I can’t do this if I have all the “other” records that don’t have a family, genus, species, or subspecies unless I put in a lot of dummy data into the fields to make each record unique. I don’t really want to do this because these miscellaneous records really don’t represent a specific species.
    So – the problem is that while I want this data separate I will need to point a column from another table to the code column in both tables.
    How is this best done? Table? View? Merge?

    Hi,
    Actually you don't have to use scope refs. Sorry but I misunderstood you earlier. Here is a complete example that does exactly what you want. Notice how I added the constraint to the materialized view. Also notice when we try to insert a code in tbl3 that doesn't exist in the view, we get an error. HTH.
    SQL> create table tbl1 (name varchar2(10), code varchar2(3) primary key);
    Table created.
    SQL> create table tbl2 (commonname varchar2(10), code varchar2(3) primary key);
    Table created.
    SQL> insert into tbl1 values ('n1','c1');
    1 row created.
    SQL> insert into tbl1 values ('n2','c2');
    1 row created.
    SQL> insert into tbl1 values ('n3','c3');
    1 row created.
    SQL> insert into tbl2 values ('name1','c1');
    1 row created.
    SQL> insert into tbl2 values ('name2','c2');
    1 row created.
    SQL> insert into tbl2 values ('name3','c3');
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> create materialized view view1 as select name, commonname, tbl1.code from tbl1, tbl2 where tbl1.code = tbl2.code;
    Materialized view created.
    SQL> select * from view1;
    NAME COMMONNAME COD
    n1 name1 c1
    n2 name2 c2
    n3 name3 c3
    SQL> create table tbl3 (code varchar2(3), record varchar2(1));
    Table created.
    SQL> alter table view1 add constraint view1pk primary key (code); -- <-Note how I added a constraint to the view
    Table altered.
    SQL> alter table tbl3 add constraint tbl3fk foreign key (code) references view1(code);
    Table altered.
    SQL> insert into tbl3 values ('c1','r');
    1 row created.
    SQL> insert into tbl3 values ('c99','r');
    insert into tbl3 values ('c99','r')
    ERROR at line 1:
    ORA-02291: integrity constraint (RAJS.TBL3FK) violated - parent key not found
    SQL> spool of;
    -Raj Suchak
    [email protected]

  • How to  Join two tables using the Inner Join

    Hi All,
    I have two tables i.e table1 and table2 as i have created two otds and my present requirement is to join this two tables and get the results and using this i need to do some logic and update another table3.
    can some one help me out how to go for the above req.
    Thanks in Advance
    Srikanth

    The best efficient way to use inner join is create two input otds,use there otd's in create a collaboration usinf etl.
    after selecting two input otd's create a inner join statement and map it to out put otd.
    while using the etl the performance of the over all integration is increased 20 time of the normal integration.
    Hopes this will helps,,
    Thanks,
    Papa Rao.

  • Joining Two Tables with a DISTINCT column value

    I have two tables I need to join, but the 'left' table I only need DISTINCT for a column.
    create table t1
      bid  number(8),
      b_number number(8),
      dset varchar2(20),
      misc varchar2(20)
    create table t2
      cid  number(8),
      track number(8)
    select bid, cid
    from   ( select bid, b_number
                from   t1
                where dset = 'ABC1234'
                and    misc = 'TEXT'
             ) x,
             ( select cid, track
               from t2
               where exists ( select 1 from t2 where t2.track = t1.b_number )
             ) z
    where x.b_number = z.trackI only need records with DISTINCT cid values, but I keep getting multiple instanced of cid.
    Any suggestions?
    Thanks!

    Maybe this?
    select distinct cid
    from t2
    where track in
    select b_number
    from t1
    where dset = 'ABC1234'
    and misc = 'TEXT'
    )

  • How to join two tables with no similar columns

    Hi all,
    I have two tables as follows:
    Table T1 have Attributes as follows:
    GLCODE,
    BRANCH,
    ITEM_NUMBER,
    DEMAND_DATE,
    QUANTITY,
    SOURCE
    Table T2 have Attributes as follows:
    FORECAST_DATE
    Now in SQL if run the following stattement iam getting out put.
    SELECT GLCODE,BRANCH,ITEM_NUMBER,DEMAND_DATE,QUANTITY, SOURCE,(SELECT DISTINCT FORECAST_DATE FROM T2) FROM T1
    The above SQL Statement giving correct results for me.
    The same SQL Statement how can we implement in mapping level?
    Regards,
    Ava

    Jaap van,
    >
    You have to specify an outer join, but how do you do that if there is no join to begin with? I would do the following (which I didn't test yet):
    add an extra column (say C_JOIN) to the T2-ingroup of the join operator and fill it with from a constant operator with say value 1. Then use T2.C_JOIN (+) = 1 as the join condition.
    If every record in T2 is guaranteed to have the same value, instead of using a deduplicator, which will read all records, sort them and deduplicate them, you can use a filter with filter condition ROWNUM < 2, which only will read one record.
    I am facing almost the same problem but not entirely thou and I was wondering if you have an idea how to even start.
    Problem:
    I got this table:SQL> desc ita.tpis32_job_status
    Name Null? Type
    JOBID NOT NULL NUMBER
    T1_ID NUMBER
    QID NUMBER
    REQ_TYPE VARCHAR2(10)
    SUBMIT_TIME DATE
    OWNERID VARCHAR2(30)
    DESCRIPTION VARCHAR2(150)
    STARTTIME DATE
    ENDTIME DATE
    STATUS VARCHAR2(50)
    ERROR_ID NUMBER
    TABLE_NAME VARCHAR2(30)
    SERVER_ID VARCHAR2(10)
    DATABASE VARCHAR2(20)
    PRIORITY NUMBER
    NUM_LINES NUMBER
    PROCESS_ID NUMBER
    QUE_TIME NUMBER
    STATUS_CODE NUMBER
    ERROR_MSG VARCHAR2(500)
    NUM_LINES_TS NUMBER
    REMOTE_STATUS NUMBER
    This the above table, i am looking for JOBID (a five digit number) like 25875.
    What I want to do is add or append this five digit number to a string to find the corresponding table in dba_tables or all_tables. The only way I have try to do this is by writing PLSQL as you see from here:
    Re: Use PLSQL to delete tables dynamically
    When the select is writing properly, the result of the five digit number from JOBID and the string should look like the below result (job_(five digit_%).
    My problem is there is no relationship between ALL_TABLES and the my own table (ita.tpis32_job_status). Any help will be appreciated.
    TABLE_NAME
    JOB_58871_OUTDATA
    JOB_58868_TS
    JOB_58868_OUTDATA
    JOB_58867_TS
    JOB_58867_CMDLBL_2
    JOB_58867_OUTDATA
    JOB_58866_TS

  • How do i join 3 table with the 'join' query ?

    Hello,
    i want to join 3 tables -> bsis, bsad and vbrp
    the components of the query to be are ,
    - select (matnr from vbrp) sum(amount from bsad).
    - join bsis and bsad on  bsisbukrs = bsadbukrs, bsisbelnr = bsadaugbl and bsisbldat = bsadaugdt.
    - where bsisblart = 'DZ' and bsishkont = '123456'.
    - join bsad and vbrp on vbrpburks = bsadbukrs, vbrpgjahr = bsadgjahr and vbrpbelnr = bsadbelnr.
    The double join query is to be constructed out of the above components.
    Thanks,
    Shehryar Dahar

    c an example....
    DATA: BEGIN OF wa,
            carrid TYPE spfli-carrid,
            connid TYPE spfli-connid,
            fldate TYPE sflight-fldate,
            bookid TYPE sbook-bookid,
          END OF wa,
          itab LIKE SORTED TABLE OF wa
                    WITH UNIQUE KEY carrid connid fldate bookid.
    SELECT  pcarrid pconnid ffldate bbookid
      INTO  CORRESPONDING FIELDS OF TABLE itab
      FROM  ( ( spfli AS p
                INNER JOIN sflight AS f ON pcarrid = fcarrid AND
                                           pconnid = fconnid    )
                INNER JOIN sbook   AS b ON bcarrid = fcarrid AND
                                           bconnid = fconnid AND
                                           bfldate = ffldate     )
      WHERE p~cityfrom = 'FRANKFURT' AND
            p~cityto   = 'NEW YORK'  AND
            fseatsmax > fseatsocc.
    LOOP AT itab INTO wa.
      AT NEW fldate.
        WRITE: / wa-carrid, wa-connid, wa-fldate.
      ENDAT.
      WRITE / wa-bookid.
    ENDLOOP.
    Ramesh.

  • Headphones making a cracking noise. Headphones are not broken, it was all working fine but all of a sudden the cracking noise has developed. Please help!

    Can someone please help. My headphones are in full working order and I have had no issue using them to listen to music or watch movies on my MBP. However since yesterday there is an awful cracking sound when they are inserted in to the jack port. Music plays fine through MBP but not when headphones are inserted. There is plenty of examples of this happening on the internet but there does not seem to be a lot of advice on how to rectify this problem. I would be very grateful if someone could help.

    Can someone please help. My headphones are in full working order and I have had no issue using them to listen to music or watch movies on my MBP. However since yesterday there is an awful cracking sound when they are inserted in to the jack port. Music plays fine through MBP but not when headphones are inserted. There is plenty of examples of this happening on the internet but there does not seem to be a lot of advice on how to rectify this problem. I would be very grateful if someone could help.

  • Hi -since i installed verion 6.0.1 my ipad 2 crashes continuously and freezes up at least 5x a day- it is the worst it has ever been - please help

    My ipad 2 crashes ll the time since  the new update has been installed. Apps bomb out and the ipad freezes up

    1. Close all inactive apps in the Task Bar. Double-click the Home button and hold apps down for a second or two and tap the minus sign to close app.
    2. Try a reset. Hold the Sleep and Home button down for about 10 seconds until you see the Apple Logo

  • Join two tables with the same information

    I have a registration database. It references two other tables. I accept registrations from Faculty and from Students, but their information is in two different tables. Both have fname and lname. If they have people_id filled in, I want the fname and lname from the People table. If they have student_id filled in, I want it from the Student table.
    I've never done this sort of IF situation. Here are the tables:
    create table passport_registration (
         passport_registration_id NUMBER Primary Key,
         date_added date,
         student_id NUMBER REFERENCES students(student_id),
         people_id NUMBER REFERENCES people(id),
         passport_listing_id NUMBER REFERENCES passport_listing(passport_listing_id)
    create table PEOPLE (
    id NUMBER Primary Key,
    dateModified date,
    fname VARCHAR2(100),
    lname VARCHAR2(100)
    create table students (
         student_id NUMBER Primary Key,
         date_added date,
         s_uid VARCHAR2(50),
         fname VARCHAR2(50),
         lname VARCHAR2(50)
    Any sort of assistance is appreciated.
    Thank you.
    daniel

    (It'd be helpful if you could edit your post and stick {noformat} before and after your sql statement - that will format it so that the (+){noformat} show correctly instead of being converted to the (+) symbol!)
    As to the questions:
    1. You've got two columns that have a decision to be made on them; you're going to need to write two sets of decision-making code, one for each column. I guess you could also do something like:select a.col1, d.col2, d.col3
    from table1 a, (select 'table2' cola, b.col1, b.col2, b.col3 from table2 b
    union all
    select 'table3' cola, c.col1, c.col2, c.col3 from table3 c) d
    where a.col1 = d.col1
    and nvl2(a.col2, 'table3', 'table2') = d.cola;
    nb, not tested, and I'm up far too late, so could have made an easy mistake!
    2. Yes, {noformat} (+){noformat} is the oracle method of doing outer joins; it could be rewritten into ansi joins if you like; I'm just not that familiar with them to do it myself!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Error joining two tables in graph pane

    While trying to join two tables by draging one column onto a column of another table in a graph pane, an error dialog with the following message appears:
    "Drag and drop failed. Please drag a column from one table in the graph onto a column of another table in the graph pane. If you are trying to create a self join, please create another instance of the table and adding same table to the graph pane."
    How do join two tables in the query editor graphically?

    I also have the same problem. I use MySQL. I do not have any foreign keys in my tables. If I try to create table joins graphically myself I get the following error:
    "Drag and drop failed. Please drag a column from one table in the graph onto a column of another table in the graph pane. If you are trying to create a self join, please create another instance of the table and adding same table to the graph pane."
    When I type SQL query(similar to the following) in the in the query editor it dosent work: (As a result same row is appearing more than one time when I test the application)
    WHERE login.USERNAME=me.NAME
    In the above Mayagiri suggested a turorial using Pointbase and tables with foreign keys which is not directly connected with problem.(Beacuse it seems no problems in Pointbase tables with foreign keys)
    Any further is very much appreciated. Thanks in advance.

  • Joining two tables in PL/SQL

    Hi there,
    I have two problems...first being:
    We are trying to run a sub-query within a WHERE/AND clause. I am not sure on the correct syntax on how to run the sub-query as denoted in the code below. Secondly I am trying to join two tables with a common column name (ie: CIPIDI_NR). Considering I cant fix the first problem I cant test out the sub-query. So any help on either would be grateful. Cheers
    Select *
    from TBL_CIPIDI
         WHERE CIPIDI_NR like nvl ('in_case_number%', CIPIDI_NR)
    AND CIPIDI_NAME like nvl ('in_case_name%', CIPIDI_NAME)
    AND COST_CENTRE LIKE NVL ('in_cost_centre%', COST_CENTRE)
    AND CIPIDI_DESCRIPTION like nvl ('in_description%', CIPIDI_DESCRIPTION)
    AND CLAIMANT_NAME LIKE NVL ('in_claimant%', CLAIMANT_NAME)
    AND REQUESTOR LIKE NVL ('in_requestor%', REQUESTOR)
    AND PROJECT_MANAGER LIKE NVL ('in_project_manager%', PROJECT_MANAGER)
    AND TEAM_LEADER LIKE NVL ('in_team_leader%', TEAM_LEADER)
         AND ********RUN THE QUERY BELOW************
    SELECT C1.CIPIDI_NR, C2.CIPIDI_NR
    from TBL_TEAM_MEMBERS C1, TBL_CIPIDI C2
         WHERE C1.CIPIDI_NR = C2.CIPIDI_NR
         AND TEAM_MEM_NAME LIKE NVL ('in_team_mem_name%', TEAM_MEM_NAME)
    );

    You really need to start providing create table and insert statements for tables and sample data for testing, the results that you want based on that data in order to clarify the problem, your Oracle version, and a copy and paste of an attempted run of your code, complete with any error messages received. The following is my best guess at what you might be looking for.
    Select *
    from   TBL_TEAM_MEMBERS C1, TBL_CIPIDI C2
    WHERE  C1.CIPIDI_NR = C2.CIPIDI_NR
    AND    c1.CIPIDI_NR          like nvl (in_case_number     || '%', c1.CIPIDI_NR)
    AND    c1.CIPIDI_NAME        like nvl (in_case_name       || '%', c1.CIPIDI_NAME)
    AND    c1.COST_CENTRE        LIKE NVL (in_cost_centre     || '%', c1.COST_CENTRE)
    AND    c1.CIPIDI_DESCRIPTION like nvl (in_description     || '%', c1.CIPIDI_DESCRIPTION)
    AND    c1.CLAIMANT_NAME      LIKE NVL (in_claimant        || '%', c1.CLAIMANT_NAME)
    AND    c1.REQUESTOR          LIKE NVL (in_requestor       || '%', c1.REQUESTOR)
    AND    c1.PROJECT_MANAGER    LIKE NVL (in_project_manager || '%', c1.PROJECT_MANAGER)
    AND    c1.TEAM_LEADER        LIKE NVL (in_team_leader     || '%', c1.TEAM_LEADER)
    AND    TEAM_MEM_NAME         LIKE NVL (in_team_mem_name   || '%', TEAM_MEM_NAME);

  • Join two table (Inner Join)

    how to join two tables using inner join.

    Tariq,
    Pretty vague question.  You can create joins in an ABAP program, or while creating a view, or when creating a SAP query of one type or another.  Some people download tables and then join them using desktop software.  If you can elaborate your question I may be able to give you a better answer.
    I recently joined two wooden tables at a picnic.  I used 24 gauge galvanized wire combined with duct tape, so I guess you couldn't really call that an 'inner join'.
    Best Regards,
    DB49

Maybe you are looking for