1

Background:

I have a table in an Access database (let's call it [tblMyTable]). The table has thousands of entries for each month, with each entry belonging to a category, e.g:

ID  Month  Category
--  -----  --------
 1      1  White
 2      1  Black
 3      2  White
...etc.

Problem:

When I run my (somewhat simplified) query

SELECT tblMyTable.Month, COUNT(tblMyTable.ID) AS CountedIDs 
FROM tblMyTable 
WHERE tblMyTable.Category = "Black" 
GROUP BY tblMyTable.Month

the return is:

Month  Count
-----  -----
    1      1

whereas what I expect/need is:

Month  Count
-----  -----
    1      1
    2      0

I've tried using the NZ() function to force a '0' return, but not having any luck with that either, hence reaching out to everyone here...

If anything is missing or looks weird with the above, please shout out and I'll try to address it.

4

1 回答 1

1

像这样创建一个名为 [MonthNumbers] 的表

MonthNumber
-----------
          1
          2
          3
          4
          5
          6
          7
          8
          9
         10
         11
         12

然后使用以下查询(其中包括您的原始查询作为子查询):

SELECT 
    mn.MonthNumber AS Month,
    Nz(gb.CountedIDs, 0) AS CountedIDs
FROM
    MonthNumbers mn
    LEFT JOIN
    (
        SELECT 
            tblMyTable.Month, 
            COUNT(tblMyTable.ID) AS CountedIDs 
        FROM tblMyTable 
        WHERE tblMyTable.Category = "Black" 
        GROUP BY tblMyTable.Month
    ) gb
        ON gb.Month = mn.MonthNumber

它返回

Month  CountedIDs
-----  ----------
    1  1         
    2  0         
    3  0         
    4  0         
    5  0         
    6  0         
    7  0         
    8  0         
    9  0         
   10  0         
   11  0         
   12  0         
于 2013-11-11T10:01:05.363 回答