sql没有返回正确的计数

时间:2013-08-24 08:29:28

标签: sql sql-server sql-server-2008 tsql

我有像这样的SQL表hr_RegistrantCategories:

RegistrantID    CategoryID
1   47
4   276
4   275
4   278
4   274
4   277
16276   276
16276   275
16276   278
16295   276
16295   275
16295   278
16295   274
16295   277
16292   276
16292   275
16292   278
16292   274
16292   277
16293   276
16293   275
16293   278
16293   274
16293   277
16294   276
16294   275
16294   278
16294   274
16294   277
16303   276
16303   275
16303   278
16303   274
16303   277
16302   276
16302   275
16302   278
16302   274
16302   277
16303   276
16303   275
16303   278
16303   274
16303   277
16304   276
16304   275
16304   278
16304   274
16304   277
26  276
26  275
26  278
26  274
26  277
16305   276
16305   275
16305   278
16305   274
16305   277
29  276
29  275
29  278
29  274
29  277
16306   276
16306   275
16306   278
16306   274
16306   277
16306   276
16306   275
16306   278
16306   274
16306   277
16307   276
16307   275
16307   278
16307   274
16307   277
16307   276
16307   275
16307   278
16307   274
16307   277

和另一个表hr_categories如下:

CategoryID
1
2
3
4
5
6
...
..
..
700

但是当我使用以下查询

时,它返回结果中的相同计数
SELECT  COUNT(RC.RegistrantID)
            FROM dbo.hr_Registrants R INNER JOIN dbo.hr_RegistrantCategories RC ON R.RegistrantID = RC.RegistrantID
            WHERE R.Deleted = 0 
            AND RC.CategoryID IN (SELECT CategoryID FROM dbo.hr_Categories)


            SELECT C.CategoryID,
            (
           SELECT  COUNT(DISTINCT RC.RegistrantID)
            FROM dbo.hr_Registrants R INNER JOIN dbo.hr_RegistrantCategories RC ON R.RegistrantID = RC.RegistrantID
            WHERE R.Deleted = 0 
            AND RC.CategoryID IN (SELECT CategoryID FROM dbo.hr_Categories C1 WHERE C1.Deleted = 0)


        )AS RegistrantsCount
        FROM dbo.hr_Categories C

结果是:

CategoryID  RegistrantsCount
1   13
2   13
3   13
4   13
5   13
6   13
7   13
8   13

2 个答案:

答案 0 :(得分:1)

内部查询与外部查询不相关,因此它为每一行返回相同的值。

SELECT C.CategoryID,
        (
       SELECT  COUNT(DISTINCT RC.RegistrantID)
        FROM dbo.hr_Registrants R INNER JOIN dbo.hr_RegistrantCategories RC ON R.RegistrantID = RC.RegistrantID
        WHERE R.Deleted = 0 
        AND RC.CategoryID IN (SELECT CategoryID FROM dbo.hr_Categories C1 WHERE C1.Deleted = 0)

        AND RC.CategoryID = C.CategoryID -- correlate with the outer query

)AS RegistrantsCount
    FROM dbo.hr_Categories C

答案 1 :(得分:1)

我认为这个查询可以满足您的需求。我正在使用LEFT JOIN因为我想您也想知道计数是否为0?如果没有,您可以将其设为INNER JOIN

SELECT C.CategoryID, COUNT(RC.RegistrantID) AS RegistrantsCount
    FROM dbo.hr_categories C
    LEFT JOIN dbo.RegistrantCategories RC
        ON RC.CategoryID = C.CategoryID
    LEFT JOIN dbo.hr_Registrants R
        ON R.RegistrantID = RC.RegistrantID
        AND R.Deleted = 0
    WHERE C.Deleted = 0
    GROUP BY C.CategoryID