SQL查询使用连接获取计数

时间:2015-04-16 17:18:07

标签: sql-server tsql stored-procedures

我有一个非常简单的查询,我用来获得两个单独的计数。我遇到的问题是,通过加入,我得到了不准确的数字偏差。

有没有更好的方法从不同的表中获取两个单独的计数?

SELECT   g.[group] AS groupName,
         COUNT(d.departmentDesc) AS total,
         COUNT(skg.Skillset) AS totalSkillsets
FROM     dbo.TFS_Groups AS g
         LEFT OUTER JOIN
         TFS_Departments_Groups AS d
         ON g.[group] = d.tfsGroup
         LEFT OUTER JOIN
         TFS_Skillsets_Groups AS skg
         ON skg.tfsGroup = g.[Group]
GROUP BY g.[group]
ORDER BY groupName ASC;

2 个答案:

答案 0 :(得分:2)

如果您使用唯一值后,可以将DISTINCT放入COUNT中 即。

SELECT   g.[group] AS groupName,
         COUNT(DISTINCT d.departmentDesc) AS total,
         COUNT(DISTINCT skg.Skillset) AS totalSkillsets
...

我怀疑问题在于你有两个一对多的关系导致额外的行。

减少这种情况的方法是在子查询中预聚合,即

SELECT   g.[group] AS groupName,
         d.vol AS total,
         skg.vol AS totalSkillsets

FROM     dbo.TFS_Groups AS g

         LEFT OUTER JOIN
         (SELECT tfsgroup, count(*) as Vol 
         FROM   TFS_Skillsets_Groups
         group by tfsgroup) AS skg
         ON skg.tfsGroup = g.[Group]

         LEFT OUTER JOIN
         (SELECT tfsgroup, count(*) as Vol 
         FROM   TFS_Departments_Groups 
         group by tfsgroup) AS d
         ON d.tfsGroup = g.[Group]

ORDER BY groupName ASC;

答案 1 :(得分:0)

尝试APPLY

SELECT   g.[group] AS groupName,
         ca1.c1 AS total,
         ca2.c2 AS totalSkillsets
FROM     dbo.TFS_Groups AS g
OUTER APPLY (SELECT COUNT(*) AS c1 FROM TFS_Departments_Groups AS d WHERE g.[group] = d.tfsGroup) ca1
OUTER APPLY (SELECT COUNT(*) AS c2 FROM TFS_Skillsets_Groups AS skg WHERE g.[group] = skg.tfsGroup) ca2