I have two tables and I’m selecting data from the first table. If the condition is meet(Alias type = 2) and the data in second table for the id from the first table exist the I want to select the column from the second table. Here is data to explain more:
Table 1
id | Name | Location
---+--------------+---------
34 |John Smith |NewYork
36 |Mike Smith |London
45 |Bob Smith |Los Angeles
Table 2
id | Alias | Alias type
---+-------------------+-------
36 |Warren Johnson |1
36 |William Williams |2
Wanted results if alias type = 2
id |Name | Location
---+-------------------+---------
34 |John Smith |NewYork
36 |William Williams |London
45 |Bob Smith |Los Angeles
Can you help me write query to get the wanted results? Tell me if I need to explain more. I’m using a SQL Server database.
You can use a
left outer joinonto Table2, and thenCOALESCEthe Alias and Name results like this:COALESCEworks by finding the first non-null value in the supplied values.