Joining Two Tables

  • Hi Guys,

    I have two tables Table1 and Table2. I need to create Table 3. I am not sure how to join the two tables to create Table3.

    Table1

    ID Label Value

    1&nbsp&nbsp A&nbsp&nbsp&nbsp&nbsp 10

    2 &nbsp&nbspB &nbsp&nbsp&nbsp&nbsp 20

    3&nbsp&nbsp C &nbsp&nbsp&nbsp&nbsp 5

    Table 2

    ID Label Value

    1&nbsp&nbsp A&nbsp&nbsp&nbsp&nbsp 5

    2&nbsp&nbsp D&nbsp&nbsp&nbsp&nbsp 10

    3&nbsp&nbsp E &nbsp&nbsp&nbsp&nbsp20

    Table 3

    Label Table1.Value Table2.Value

    A &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp 10&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp5

    B &nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp 20

    C &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp 5

    D &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp 10

    E &nbsp&nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp 20

  • INNER JOINS (msdn) really are the basics on SQL. I would suggest reading on the matter, rather than asking for someone to write you SQL for what looks like a homework question.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • You will need a FULL OUTER JOIN

    DECLARE @Table1 TABLE (ID INT, Label VARCHAR(10), Value INT)

    DECLARE @Table2 TABLE (ID INT, Label VARCHAR(10), Value INT)

    INSERT @Table1

    SELECT 1, 'A', 10 UNION ALL

    SELECT 2, 'B', 20 UNION ALL

    SELECT 3, 'C', 5

    INSERT @Table2

    SELECT 1, 'A', 5 UNION ALL

    SELECT 2, 'D', 10 UNION ALL

    SELECT 3, 'E', 20

    SELECT ISNULL( T1.Label, T2.Label ) AS Label,

    T1.Value AS Table1Value,

    T2.Value AS Table2Value

    FROM @Table1 AS T1

    FULL OUTER JOIN @Table2 AS T2

    ON T1.Label = T2.Label


    Kingston Dhasian

    How to post data/code on a forum to get the best help - Jeff Moden
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply