Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join 2 tables in SQL Server

Tags:

sql

sql-server

I have 2 tables as following:

Table_1

    CODE1    CODE2     CODE3    SYNC
    -----------------------------------
    02       03         04         YES
    01       03         NULL         NO
    01       02         03         NA

Table_2

    CODE     NAME
    --------------
    01       ABC
    02       BCD
    03       DEF
    04       EFG

How to create the query as the following result:

    CODE1     CODE2       CODE3      SYNC
    --------------------------------------
    BCD       DEF         EFG         YES
    ABC       DEF         NULL        NO
    ABC       BCD         DEF         NA
like image 376
user197267 Avatar asked Oct 01 '22 04:10

user197267


2 Answers

Try using left join:

SELECT
    tblCODE1.NAME AS CODE1,
    tblCODE2.NAME AS CODE2,
    tblCODE3.NAME AS CODE3,
    Table_1.SYNC
FROM
    Table_1
    LEFT JOIN Table_2 as tblCODE1
        ON tblCODE1.CODE=Table_1.CODE1
    LEFT JOIN Table_2 as tblCODE2
        ON tblCODE2.CODE=Table_1.CODE2
    LEFT JOIN Table_2 as tblCODE3
        ON tblCODE3.CODE=Table_1.CODE3
like image 182
Arion Avatar answered Oct 13 '22 11:10

Arion


This is what you need to do

SELECT T2.CODE AS [CODE1],T3.CODE AS [CODE2],T4.CODE AS [CODE3],T.SYNC
FROM Table_1 T
LEFT JOIN Table_2 T2 ON T2.CODE = T.CODE1
LEFT JOIN Table_2 T3 ON T3.CODE = T.CODE2
LEFT JOIN Table_2 T4 ON T4.CODE = T.CODE3
like image 34
Naveen Avatar answered Oct 13 '22 11:10

Naveen