如何选择在SQL Server中的Junction表中映射的重复值

时间:2018-03-08 14:02:36

标签: sql sql-server join duplicates

我创建了Employee,Department和EmpDept Table。

这里的EmpDept表是Junction Table。

EmpDept(Junction Table)

EmpID           DeptID

101         502

103         501

102         504

104         502

105         502

106         505

107         507

108         509

在这里," EmpId "引自" 员工"表和" EmpId "是主键," DeptId " 是从" 部门"引用的表

 Employee

EmpID   EmpName     

    101 Shama

    103 Varun   

    102 Joesph

    104 Ram

    105 Ravi

    106 Deva

    107 Mukund

此处 EmpId是主键

Department

DeptName    DeptID

x       501

        502

J       503

R       504

A       505

D       506

M       507

z       508

C       509

现在,我必须获得 EmpDept 表中的重复值,并显示具有相同名称的相应 EmpName

1 个答案:

答案 0 :(得分:0)

declare @DepIDTemp int
set @DepIDTemp=(select EmpDept.DepartmentId
from EmpDept
group by EmpDept.DepartmentId
 having count(EmpDept.DepartmentId)>1) 
 Select DEPARTMENT.DepartmentId, DepartmentName,EMPLOYEE.EmployeeName,EMPLOYEE.EmployeeId from
 DEPARTMENT
 join EmpDept on EmpDept.DEPARTMENTID=DEPARTMENT.DepartmentId
 join EMPLOYEE on EmpDept.EMPLOYEEID=EMPLOYEE.EmployeeId
 where DEPARTMENT.DepartmentId=@DepIDTemp;

这是我的解决方案。