I am trying to write the query for existing table data. TABLE_A and TABLE_B has one record but TABLE_C has 2 records. One for Home address and other is for Work address.
So the following query returns 2 records. I am trying to get only one record out of 2 records.
If CITY is NULL, state_id is null for address_type = 1(Home) then get Work(address_type = 2) address. If both are null then get ‘Home’ address. What is the best way to achieve this functionality.
Thank you for any suggestion.
select a.A_ID, a.B_ID, a.A_DESC, b.first_name, b.last_name, c.address_type, c.city, c.state
from table_A a
left join table_B b on b.B_ID = a.B_ID
left join table_C c on c.B_id = b.B_id
where a.A_ID = 10
TABLE_A
A_ID int
B_ID int
A_Desc varchar(20)
TABLE_B
B_ID int
first_name varchar(30)
last_name varchar(30)
TABLE_C
C_ID int
B_ID int
address_type int
city varchar(50)
state int
Result:
A_ID B_ID A_DESC first_name last_name address_type city state
--------------------------------------------------------------------------------
10 200 test_ name1 name_last 1 NULL NULL
10 200 test_ name1 name_last 2 City_test 2
I want this final result
A_ID B_ID A_DESC first_name last_name address_type city state
--------------------------------------------------------------------------------
10 200 test_ name1 name_last 2 City_test 2
1 Answer