SQL计数,其中关系不存在

时间:2015-02-02 11:24:28

标签: sql relationships

我有一个3个表,其中一个包含事件列表,另一个包含用户列表,最后一个包含事件和用户之间的关系。可能有多个与事件相关的不同类型的用户(受影响的用户或分配给用户,每个用户都拥有自己的关系类)我试图生成一个查询,该查询将显示分配给每个用户的事件数量以及事件没有分配给用户。我有以下查询来获取用户列表:

SELECT MTV_System$Domain$User.DisplayName as Analyst, COUNT(MTV_System$WorkItem$Incident.Id_9A505725_E2F2_447F_271B_9B9F4F0D190C) AS Incidents
FROM RelationshipView
INNER JOIN MTV_System$Domain$User ON RelationshipView.TargetEntityId=MTV_System$Domain$User.BaseManagedEntityId
INNER JOIN MTV_System$WorkItem$Incident ON RelationshipView.SourceEntityId=MTV_System$WorkItem$Incident.BaseManagedEntityId
WHERE RelationshipView.RelationshipTypeId='15E577A3-6BF9-6713-4EAC-BA5A5B7C4722'  AND RelationshipView.IsDeleted='0' AND  MTV_System$WorkItem$Incident.Status_785407A9_729D_3A74_A383_575DB0CD50ED = '5E2D3932-CA6D-1515-7310-6F58584DF73E'

GROUP BY MTV_System$Domain$User.DisplayName

但是,这不允许我查看有多少事件没有用户。我创建了这个查询,它用关系

从数字中减去事件的数量
Select (Select COUNT(MTV_System$WorkItem$Incident.Id_9A505725_E2F2_447F_271B_9B9F4F0D190C) FROM MTV_System$WorkItem$Incident
WHERE MTV_System$WorkItem$Incident.Status_785407A9_729D_3A74_A383_575DB0CD50ED = '5E2D3932-CA6D-1515-7310-6F58584DF73E') -
(SELECT COUNT(MTV_System$WorkItem$Incident.Id_9A505725_E2F2_447F_271B_9B9F4F0D190C)
FROM RelationshipView
INNER JOIN MTV_System$WorkItem$Incident ON RelationshipView.SourceEntityId=MTV_System$WorkItem$Incident.BaseManagedEntityId
WHERE RelationshipView.RelationshipTypeId='15E577A3-6BF9-6713-4EAC-BA5A5B7C4722'  AND RelationshipView.IsDeleted='0' AND  MTV_System$WorkItem$Incident.Status_785407A9_729D_3A74_A383_575DB0CD50ED = '5E2D3932-CA6D-1515-7310-6F58584DF73E'
) AS 'Incidents'

但是,这是一个单独的查询,而不是之前结果中的“未分配”值。

如何组合2个查询以获得如下所示的结果:

Analyst    | No Incidents
Bob        |     5
Dave       |     4
Unassigned |     6

由于

1 个答案:

答案 0 :(得分:3)

您希望left join获取不匹配的内容。为此,您希望从Incident表开始,因为它包含您要保留的所有内容。最重要的是将条件从where子句移到on子句:

SELECT u.DisplayName as Analyst, 
       COUNT(r.SourceEntityId) AS Incidents
FROM MTV_System$WorkItem$Incident i LEFT JOIN
     RelationshipView r
     ON r.SourceEntityId = i.BaseManagedEntityId AND
        r.RelationshipTypeId = '15E577A3-6BF9-6713-4EAC-BA5A5B7C4722'  AND
        r.IsDeleted ='0'LEFT JOIN
     MTV_System$Domain$User u
     ON r.TargetEntityId = u.BaseManagedEntityId         
WHERE i.Status_785407A9_729D_3A74_A383_575DB0CD50ED = '5E2D3932-CA6D-1515-7310-6F58584DF73E'
GROUP BY u.DisplayName

注意我还添加了表别名。这些使查询更容易编写和阅读。

编辑:

我想你想要:

SELECT COALESCE(u.DisplayName, 'Not Assigned') as Analyst, 
       COUNT(r.SourceEntityId) AS Incidents
. . .