Question

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!

Was it helpful?

Solution

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 <.....>

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top