SQL count()与group不返回0/0记录

时间:2009-12-16 20:38:54

标签: sql ms-access count

为便于讨论,请在Access ...

中考虑此基本表(测试)
ID  division  name   role
1    1        Frank  100
2    2        David  101
3    3        John   101
4    2        Mike   102
5    2        Rob    102
7    3        Dave   102
8    3        Greg   102

我想计算某个部门中某个角色的用户。如果我做一个简单的count(),我会返回正确的0:

SELECT COUNT(ID) as ct 
FROM Test 
WHERE role >=101 and division=1;

产量

division   ct
    1       0

但是,我想在结果中包含分区编号(为了进一步加入,报告等),它总是返回null / no行而不是除以0和0的分数:

SELECT division, COUNT(ID) as ct 
FROM Test WHERE role >=101 
GROUP BY division 
HAVING division=1;

SELECT division, COUNT(ID) as ct 
FROM Test 
WHERE role >=101 AND division=1 
GROUP BY division;

产量

division   ct

我最初想到的是因为如果用户输入不在表格中的分部(如4),我也希望这样做...

SELECT division, COUNT(ID) as ct 
FROM Test 
WHERE role >=101 AND division IN (1,2,4) 
GROUP BY division;

产量

division   ct
    2       3

而不是

division   ct
    1       0
    2       3
    4       0

如果计数为0,是否无法将除法与计数一起返回?

5 个答案:

答案 0 :(得分:4)

这个怎么样:

SELECT division, ISNULL(ct,0) AS ct
FROM divisionTable
LEFT JOIN
(SELECT division, COUNT(ID) as ct FROM Test WHERE role >=101 GROUP BY division) CountQuery
ON divisionTable.division = CountQuery.division
WHERE divisionTable.division IN (1,2,4)

答案 1 :(得分:2)

执行此操作的最佳方法是创建第二个表,列出所有分区(可以是单个列),然后LEFT(或右键)将其加入查询,因此您确定它将列出所有分区。

答案 2 :(得分:2)

这适用于SQL服务器,所以也许......

SELECT  division, COUNT(ID) AS ct
FROM    Test
WHERE   role >= 101
GROUP BY ALL division
HAVING  division = 1 ;

答案 3 :(得分:1)

我不确定如何在Access中正确地执行此操作,但是这样可以确保结果集中始终至少有一行:

SELECT *
FROM Test 
WHERE role >=101 AND division IN (1,2,4) 
UNION
SELECT 1 as ID, 1 as division, 'Dummy' as Name, 100 as role
FROM Dual
UNION
SELECT 1 as ID, 2 as division, 'Dummy' as Name, 100 as role
FROM Dual
UNION
SELECT 1 as ID, 4 as division, 'Dummy' as Name, 100 as role
FROM Dual

(基本上,这个语句为每个分区添加了一个虚拟记录。Dual是一个只有一条记录的虚拟Oracle表。我确信在联合中添加记录有一种更优雅的方式,但我希望这个想法能够实现。)

然后,在此记录集上按分区运行count(ID)组(可能是临时查询),并从计数中减去虚拟记录(因此select子句将

SELECT division, count(ID)-1

答案 4 :(得分:0)

您是否尝试过使用count(*)代替count(ID)?