0

I've a table EMPLOYEE which has columns like these

EmpId FName LName

I have another table ADDRESS which has columns like these

EmpId AddressType Address Phone Email 

AddressType column has 2 possible types, Residential and Official and an Emp can have both types of address.
I need a query which will join these 2 tables using EmpId.
It also needs to fetch one address which has phone not null.
If both addresses has phone, then fetch any one, if none has phone, still fetch any one.
Please help.

1
  • 1
    Please, explain your question further. Kindly, show some sample data. Also, show us what have you done already to solve your problem Commented Feb 14, 2015 at 3:42

1 Answer 1

3

The trick is to first decide which Address would be best for the Employee, based on your Phone-rule. After the prefered Address has been found, indicated by PhonePreference = 1, you can JOIN the correct Address on the Employee.

WITH AddressCTE AS ( SELECT * , ROW_NUMBER() OVER ( PARTITION BY EmpId ORDER BY CASE WHEN Phone IS NOT NULL THEN 1 ELSE 2 END, Phone ) PhonePreference FROM Address ) SELECT * FROM Employee E JOIN AddressCTE A ON E.EmpId = A.EmpId AND A.PhonePreference = 1 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.