0

I have three tables: Employee, Contact, Employee_Contact

Employee:

EMP_ID, FIRST_NAME, LAST_NAME...

CONTACT:

CONTACT_ID, TELEPHONE, MOBILE...

EMPLOYEE_CONTACT:

EMP_ID, CONTACT_ID

Employee and Contact table is mapped with Employee_Contact table. So I want to retrieve all Employees with Employee's only first contact, I tried this query but it is retrieving all the contacts related to that employee. Please check below query and let me know in case of any mistakes.

SELECT EMP.FirstName
    ,DEPT.Description AS Department
    ,CNT.Mobile
    ,CNT.Telephone
FROM MstEmp EMP
LEFT OUTER JOIN Department DEPT ON EMP.DeptID = DEPT.Department_ID
LEFT OUTER JOIN Employee_Contact EC ON EMP.EMP_ID = EC.EMP_ID
OUTER APPLY (
    SELECT TOP 1 *
    FROM Contact CONT
    WHERE EC.Contact_ID = CONT.Contact_ID
    ) CNT

Check this image for query output

Shreyas Pednekar
  • 1,285
  • 5
  • 31
  • 53

4 Answers4

0

Use Top keyword retrieve top one record.

SELECT TOP 1 EMP.FirstName, DEPT.Description AS Department, CNT.Mobile, 
CNT.Telephone
FROM MstEmp EMP
LEFT OUTER JOIN Department DEPT on EMP.DeptID = DEPT.Department_ID
LEFT OUTER JOIN Employee_Contact EC ON EMP.EMP_ID = EC.EMP_ID
OUTER APPLY(SELECT TOP 1 * FROM Contact CONT WHERE EC.Contact_ID = 
CONT.Contact_ID)CNT
VinuBibin
  • 679
  • 8
  • 19
0

Try this one:

SELECT EMP.FirstName
    ,DEPT.Description AS Department
    ,t.Mobile
    ,t.Telephone
FROM MstEmp EMP
LEFT OUTER JOIN Department DEPT ON EMP.DeptID = DEPT.Department_ID
LEFT OUTER JOIN Employee_Contact EC ON EMP.EMP_ID = EC.EMP_ID
LEFT OUTER JOIN Contact CONT ON EC.Contact_ID = (
        SELECT MIN(c.Contact_ID) c_id
        FROM Contact c
        WHERE CONT.Contact_ID = c.Contact_ID
        ) t
Mittal Patel
  • 2,732
  • 14
  • 23
0

You can use ROW_NUMBER() and get the first record for all the employees and then join it with the other tables.

SELECT EMP.FirstName,
       DEPT.Description AS Department,
       c.Mobile,
       c.Telephone
FROM MstEmp EMP
LEFT OUTER JOIN Department DEPT ON EMP.DeptID = DEPT.Department_ID
INNER JOIN (
             SELECT *,ROW_NUMBER() OVER (PARTITION BY EMP_ID ORDER BY EMP_ID) AS RN
             FROM Employee_Contact  ) EC ON EMP.EMP_ID = EC.EMP_ID
INNER JOIN Contact c ON c.Contact_ID=EC.Contact_ID
WHERE EC.RN=1
Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38
0

Give it a try:

select * from (
select E.[emp_id],
       E.[first_name], 
       E.[last_name], 
       C.*, 
       RANK() over (partition by (E.[emp_id], E.[first_name], E.[last_name]) order by (select null)) [RN]
from Employee [E]
join employee_contact [EC] on E.[emp_id] = EC.[emp_id]
join contact [C] on EC.[contact_id] = C.[contact_id]
) A where RN = 1
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69