sqlsql-serversql-server-2019

SQL adding rows to each row


I have a table like this

id   sequence  phase  characteristics
1      1        300      001
2      1        300      001
2      2        300      002
..

and another table that contain a lot of characteristics for each phase

phase  characteristics
300      003
300      004
300      005
....

I need to add all the characteristics to each id/sequence where phase is 300

For better understanding what I need is

id   sequence  phase  characteristics
1      1        300      001
1      1        300      003
1      1        300      004
1      1        300      005
2      1        300      001
2      1        300      003
2      1        300      004
2      1        300      005
2      2        300      002
2      2        300      003
2      2        300      004
2      2        300      005
..

I have attempted several solutions, could someone please offer assistance? Thank you in advance


Solution

  • If I understood you correctly, you want all records from the first table and additionally all matching records from the second table. That would mean to UNION the first table with the JOINed result of table 1 and 2.

    SELECT t1.id, t1.sequence, t1.phase, t1.characteristics
    FROM t1
    UNION ALL
    SELECT t1.id, t1.sequence, t1.phase, t2.characteristics
    FROM t1
    LEFT JOIN t2 ON t1.phase = t2.phase
    

    Remove the ALL from the UNION ALL if you don't want duplicates.