0

我想检查给定的 SubId/WorkflowId 组合是否存在记录ProcessCode = 10,相同的SubId/WorkflowId组合有一行ProcessCode20、30 和 40。下面是我正在尝试做的一个写得很糟糕的版本;我希望有一个更优雅的解决方案。这个查询基本上是在识别任何违反规则的东西。

IF EXISTS( SELECT * FROM @DataTable WHERE SubID = @SubId and WorkflowId = @WorkflowId and ProcessCode = 10)
AND (
NOT EXISTS( SELECT * FROM @DataTable WHERE SubID = @SubId and WorkflowId = @WorkflowId  and ProcessCode = 20) or 
NOT EXISTS( SELECT * FROM @DataTable WHERE SubId = @SubId and WorkflowId = @WorkflowId and ProcessCode = 30) or
NOT EXISTS( SELECT * FROM @DataTable WHERE SubID = @SubId and WorkflowId = @WorkflowId and ProcessCode = 40)
)
4

3 回答 3

2

如果您想查找所有具有 ProcessCode 10 但没有 20/30/40 的 SubID 和 WorkFlowID,您可以使用此查询而不是单独检查每个 Sub/Workflow。

SELECT 
    SubID,
    WorkFlowID
FROM @DataTable 
GROUP BY SubID, WorkFlowID
HAVING SUM(CASE WHEN ProcessCode = '10' THEN 1 ELSE 0 END) > 0
AND COUNT(DISTINCT (CASE WHEN ProcessCode IN ('20','30','40') THEN ProcessCode ELSE NULL END)) < 3

Sql 小提琴

于 2012-09-19T13:20:02.267 回答
0

像这样的东西?

IF EXISTS(
    SELECT 1 FROM @DataTable DT
    LEFT JOIN @DataTable DT2 ON DT.SubId = DT2.SubId AND DT.WorkflowId = DT2.WorkflodId AND DT2.ProcessCode IN (20, 30, 40)
    WHERE DT.ProcessCode = 10 AND DT2.ProcessCode IS NULL
)
于 2012-09-18T20:45:03.543 回答
0
IF EXISTS( SELECT * FROM @DataTable WHERE SubID = @SubId and WorkflowId = @WorkflowId and ProcessCode = 10)
AND (NOT EXISTS ( SELECT * FROM @DataTable WHERE SubID = @SubId and WorkflowId = @WorkflowId  and ProcessCode in (20, 30, 40)))
于 2012-09-19T13:25:05.350 回答