如何计算包括不存在的记录?

时间:2015-03-18 05:14:27

标签: sql ms-access

如何计算包括不存在的记录,其中应该有'0'作为计数?

这是我的表:

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     |
+------+---------+--------+

请注意:

  • 我的桌子有很多记录(约10k,不同'cust')
  • 年可能不是连续的(例如2013被跳过)
  • 随着时间的推移,我可能会有2015年,2016年等等
  • 实际查询将在MS_ACCESS'2010中执行(不确定是否有问题)

请帮助,谢谢!

4 个答案:

答案 0 :(得分:0)

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

但是这个查询将返回所有记录的计数,没有组条件。

答案 1 :(得分:0)

听起来你想要在没有调查记录的情况下计算每个x年组合的数量为零。如果是这种情况,您将需要两个表:客户和年份,然后执行以下操作:

    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

答案 2 :(得分:0)

如果您有多年的域名表和客户:

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

如果您没有域名表,您将需要以某种方式发明"发明"域名,因为你无法从无到有创造的东西。

答案 3 :(得分:0)

如果你有其他人说的域名表,那就好了。如果您只需依赖表中的数据,则以下查询将为您执行此操作。

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

如果有效,可以使用iif(isnull(sum(cnt)), 0, sum(cnt))代替coalesce(sum(cnt),0)。在MS Access中,使用iif功能,在其他数据库coalesce中使用。