我有三个表:Employee,Contact,Employee_Contact
员工:
EMP_ID, FIRST_NAME, LAST_NAME...
联系方式:
CONTACT_ID, TELEPHONE, MOBILE...
EMPLOYEE_CONTACT:
EMP_ID, CONTACT_ID
Employee和Contact表与Employee_Contact表映射。 所以我想用Employee唯一的第一次联系来检索所有员工,我尝试了这个查询,但它正在检索与该员工相关的所有联系人。请检查以下查询,如有任何错误,请通知我。
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
答案 0 :(得分:0)
使用Top关键字检索前一条记录。
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
答案 1 :(得分:0)
试试这个:
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
答案 2 :(得分:0)
您可以使用ROW_NUMBER()
获取所有员工的第一条记录,然后将其与其他表格一起加入。
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
答案 3 :(得分:0)
试一试:
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