2

I have to tables with the same layout (same columns). There is one ID and other data. I need a query that returns only one ID setting the data fields to null if that ID wasn't available at the required table.

Example:

Table A 
ID - Val1 - Val2
1 - 2 - 2
2 - 3 - 3
4 - 1 - 5

Table B
ID - Val1 - Val2
2 - 3 - 3
3 - 2 - 1
4 - 2 - 3

Result
ID - Val1A - Val2A - Val1B - Val2B
1 - 2 - 2 - NULL - NULL
2 - 3 - 3 - 3 - 3
3 - NULL - NULL - 2 - 1
4 - 1 - 5 - 2 - 3

I'm using MS SQL Server. Thanks!

SQLMenace
  • 132,095
  • 25
  • 206
  • 225
Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207

2 Answers2

4

use coalesce to grab the non null id, the other columns will be null for the non matching table

select coalesce(a.id,b.id) as ID, Val1A , Val2A , Val1B , Val2B
from TableA a
Full outer join tableB b
ON <.....>
SQLMenace
  • 132,095
  • 25
  • 206
  • 225
3
SELECT COALESCE(a.ID,b.ID) AS ID, 
      a.Val1 AS TableA_Val1, 
      a.Val2 AS TableA_Val2, 
      b.Val1 AS TableB_Val1,
      b.Val2 AS TableB_Val2
FROM TableA a
FULL OUTER JOIN TableB b
ON a.ID = b.ID

You can test it here: http://sqlfiddle.com/#!3/51b8c/3

Francis P
  • 13,377
  • 3
  • 27
  • 51