Search code examples
sqlsql-servert-sqlssms-2014

SQL/SSMS - partial data move from one table to another with two conditions


Ok...I've looked around and haven't found anything that helps me resolve my specific issue. I have a table with contents that I am trying to move (table1) to an existing table (table2) into newly created columns. table1:

CNTC_COMM_TYP_ID    CNTC_COMM_VAL   CNTC_ID COMM_TYP_ID
14                  406-444-1104        4       1
15                  406-443-2127        4       4
16                  ssands@foo.bar      4       3
17                  406-338-2181       16       1
18                  406-338-7127       16       4

table2:

CNTC_ID CNTC_NM     ST_ENTY_ID  TRBL_ID WorkPhone   CellPhone   Email   Fax
1      Poole, Andy      10     NULL    NULL         NULL    NULL    NULL
2      Goodwin, Annie NULL        5    NULL         NULL    NULL    NULL

The issue that I am having trouble with is separating the values into the appropriate column. What I'm looking for is something like:

WHERE table1.CNTC_ID = table2.CNTC_ID

and:

IF (GAIN_CNTC_COMM_TYP.CNTC_TYP_ID= 1) {
    SET WorkPhone = table1.CNTC_COMM_VAL
}
ELSE IF (table1.CNTC_TYP_ID= 2) {
    SET CellPhone = table1.CNTC_COMM_VAL
}
ELSE IF (table1.CNTC_TYP_ID= 3) {
    SET Email = table1.CNTC_COMM_VAL
}
ELSE IF (table1.CNTC_TYP_ID = 4)
    SET Fax = GAIN_CNTC_COMM_TYP.CNTC_COMM_VAL
}

I've tried putting together a CASE WHEN in SQL, but I'm struggling.


Solution

  • Pivot the data in table1 and then update table2

    ;with cte as
    (
    select  CNTC_ID,
            WorkPhone=max(case when COMM_TYP_ID = 1 then CNTC_COMM_VAL end),
            CellPhone=max(case when COMM_TYP_ID = 2 then CNTC_COMM_VAL end),
            Email=max(case when COMM_TYP_ID = 3 then CNTC_COMM_VAL end),
            Fax=max(case when COMM_TYP_ID = 4 then CNTC_COMM_VAL end)
    From Yourtable
    Group by CNTC_ID
    )
    UPDATE t2
    SET    WorkPhone = c.WorkPhone,
           CellPhone = c.CellPhone,
           Email = c.Email,
           Fax = c.Fax
    FROM   table2 t2
           JOIN cte c
             ON t2.CNTC_ID = c.CNTC_ID