这是表格:
Inspector---------DocID
T01-----------3
T01-----------5
T01-----------6
T01-----------2
T02-----------4
T02-----------3
T03-----------3
T03-----------5
我喜欢找到不拥有文档(3,5,6)的检查员,然后连接列中不存在的docID。
结果:
InspectorID-----DocID
T02--------------5,6
T03--------------6
Stuff和For XML函数可用于连接值,但我如何找到非现有值,然后在一个查询中连接它们。
答案 0 :(得分:3)
WITH cte AS
(
SELECT B.Inspector, A.DocId
FROM (SELECT DocId FROM YourTable) A, (SELECT Inspector FROM YourTable) B
WHERE A.DocID IN(3,5,6)
EXCEPT
SELECT Inspector, DocId
FROM YourTable
WHERE DocID IN(3,5,6)
);
SELECT ReportId, Docs =
STUFF((SELECT ', ' + DocId
FROM cte B
WHERE A.Inspector= B.Inspector
FOR XML PATH('')), 1, 2, '')
FROM cte A
GROUP BY Inspector