我正在尝试检查一个人姓名是否多次出现在表格中以及拉出附加信息(职位名称,部门名称,员工编号)以限制创建两个存储过程1.检查名称是否多次出现和2 。检查完成后获取附加信息。
我现在的查询现在如下,它返回多行,因为我用来加入表的ID在一个表中多次出现(一个员工可以属于多个部门,EmpID在这里多次出现,返回多个值)。
SELECT c.FirstName+ ' ' + c.LastName as emp_full_name, e.EmployeeNumber,
e.EmpID, dh.PositionTitle, d.Name as deptName, e.isActive
FROM Person.Contact c
INNER JOIN HumanResources.Employee e ON c.ContactID = e.ContactID
INNER JOIN HumanResources.EmployeeDepartmentHistory dh ON e.EmpID = dh.EmpID
INNER JOIN HumanResources.Department d ON dh.DepartmentID = d.DepartmentID
WHERE c.FirstName+ ' ' + c.LastName LIKE @empName
我的一般表格结构如下:
的ContactID
姓
名字
的EmpID
EmployeeNumber
isActive
DepartmentHistoryId
的EmpID
DepartmentID的
POSITIONTITLE
DepartmentID的
名称
示例结果集:
John Doe 1234567 1 Database Architect Administration A
John Doe 1234567 1 Database Tester Administration A
答案 0 :(得分:1)
使用Distinct关键字
SELECT distinct c.FirstName+ ' ' + c.LastName as emp_full_name, e.EmployeeNumber,
e.EmpID, STUFF((
SELECT ',' + edh.PositionTitle
FROM dbo.EmployeeDepartmentHistory edh
WHERE edh.EmpID = e.EmpID
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''), e.isActive
FROM Person.Contact c
INNER JOIN HumanResources.Employee e ON c.ContactID = e.ContactID
INNER JOIN HumanResources.EmployeeDepartmentHistory dh ON e.EmpID = dh.EmpID
INNER JOIN HumanResources.Department d ON dh.DepartmentID = d.DepartmentID
WHERE c.FirstName+ ' ' + c.LastName LIKE @empName
Group By e.EmpID