如何计算不包括现有记录?

How to do a count including not existing records?

如何对不包括现有记录的计数进行计数?

这是我的 table:

CREATE TABLE SURVEY
(year CHAR(4),
cust CHAR(2));
INSERT INTO SURVEY VALUES ('2011', 'AZ');
INSERT INTO SURVEY VALUES ('2011', 'CO');
INSERT INTO SURVEY VALUES ('2012', 'ME'); 
INSERT INTO SURVEY VALUES ('2014', 'ME'); 
INSERT INTO SURVEY VALUES ('2014', 'CO');
INSERT INTO SURVEY VALUES ('2014', 'ME'); 
INSERT INTO SURVEY VALUES ('2014', 'CO');

我试过了,当然它缺少零计数:

select cust, year, count(*) as count from SURVEY
group by cust, year

我想要这样的结果:

+------+---------+--------+
| cust |    year |  count |
+------+---------+--------+
| AZ   |    2011 |  1     |
| AZ   |    2012 |  0     |
| AZ   |    2014 |  0     |
| CO   |    2011 |  1     |
| CO   |    2012 |  0     |
| CO   |    2014 |  2     |
| ME   |    2011 |  0     |
| ME   |    2012 |  1     |
| ME   |    2014 |  2     |
+------+---------+--------+

请注意:

请帮忙,谢谢!

select cust, year, (select count(cust) from survey) as count
  from SURVEY
group by cust, year

但此查询将 return 所有记录的计数,没有分组条件。

听起来您想要在不存在调查记录的情况下对每个客户 x 年组合进行计数,其中一个为零。如果是这种情况,您将需要另外两个表:customers 和 years,然后执行以下操作:

    select leftside.cust, leftside.year, count(survey.cust) from
(select * from customers, years) as leftside left join survey
on leftside.cust = survey.cust and 
leftside.year = survey.year 
group by leftside.cust, leftside.year

如果您有一个域 table 多年并且客户:

select y.year, c.cust, count(s.year) as cnt
from customer as c
cross join year as y
left join survey as s
    on s.year = y.year
    and s.cust = c.cust
group by y.year, c.cust

如果 ms-access 没有交叉连接,你可以做同样的事情:

from customer as c
join year as y
    on 1 = 1

如果您没有域 table,您将需要 "invent" 域,因为您无法从无到有。

如果您像其他人所说的那样拥有域 table,那很好。如果您只需要依赖 table 中的数据,下面的查询将为您完成。

select cp.cust, cp.year, iif(isnull(sum(cnt)), 0, sum(cnt)) as count from
(select * from (
 (select distinct cust from survey) as c cross join
 (select distinct year from survey) as y)
) cp left join
(select *, 1 as cnt from survey) s on cp.cust=s.cust and cp.year=s.year
group by cp.cust, cp.year
order by cp.cust,cp.year

如果可行,您可以使用 coalesce(sum(cnt),0) 而不是 iif(isnull(sum(cnt)), 0, sum(cnt))。在 MS Access 中使用 iif 函数,在其他数据库中 coalesce 有效。