我有这样的 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