2

我有两张桌子。

员工

EmployeeID, EmployeeName, DocumentType

文档类型

DocumentTypeID, DocumentType

有多个员工和多个文档类型。

对于每个员工,我试图显示哪些 DocumentTypes 不存在。

我似乎无法为每个 EmployeeID/Employee Name 执行此操作。我只能获取所有员工都不存在的 DocumentTypes 列表。

我可以在没有光标穿过每个 EmployeeID 的情况下执行此操作吗?

4

3 回答 3

0

我猜你正在寻找类似这样的数据

EmployeeID EmployeeName DocumentTypeNotMapped
1          abc          doctype1, doctype3, doctype4
2          def          doctype3, doctype2, doctype7

使用查询

SELECT ET.EmployeeID, ET.EmployeeName,
SELECT LEFT(DocumentType, LEN(DocumentType) - 1)
FROM (
    SELECT DISTINCT DocumentType + ', '
    FROM DocumentTypeTable 
    WHERE DocumentType != ET.DocumentType 
    FOR XML PATH ('')
  ) D (DocumentType)
FROM EmployeeTable ET
于 2012-07-19T06:06:22.027 回答
0

编辑更好的版本

select distinct e.EmployeeID, e.EmployeeName, t.DocumentTypeID, t.DocumentType
from Employee e
cross join DocumentType t
left join Employee e2 on e2.EmployeeID = e.EmployeeID and t.DocumentTypeID = e2.DocumentTypeID
where e2.EmployeeID is null

原创- 这可行,但感觉不是最优雅的解决方案

select distinct e.EmployeeID, e.EmployeeName, dt.DocumentTypeID, dt.DocumentType
from Employee e
outer apply (
    select * from DocumentType t
    where not exists (
        select 1 
        from Employee e2 
        where e2.DocumentTypeID = t.DocumentTypeID 
        and e2.EmployeeID = e.EmployeeID)
) dt
于 2012-07-19T06:11:35.397 回答
0

假设您使用的是 sql server

;with cte as (
select E.EmployeeID, E.DocumentType,D.DocumentTypeID from Employee E
 left outer join Document D
on E.DocumentType<>D.DocumentTypeID),
cte1 as (select EmployeeID,DocumentTypeID  from cte
group by  EmployeeID,DocumentTypeID
having count(*)>1)
select * from cte1
union all
select EmployeeID,DocumentTypeID from cte where EmployeeID not in
(select EmployeeID from cte1)
order by EmployeeID,DocumentTypeID 
于 2012-07-19T06:44:13.387 回答