如何在MS-Access的计数查询中为空值返回零值?

时间:2018-11-10 00:54:32

标签: sql ms-access

我尝试在MS-Access的查询中检索两个打开类型。如下图所示。当我的结果中同时出现这两个值时,它们将产生每个位置所处位置的数量。

Opening Types

在相关表格上根本没有选择任何一种开门类型时,它不会显示在查询计数上,如下所示。

Only 1 category displaying

我的SQL如下

var formData = JSON.stringify({
    SchoolId: $('#SchoolId').val(),
    Name: $('#Name').val(),
})

我尝试更改联接,但没有运气。任何帮助将不胜感激。

有些示例数据与我的数据库使用的数据相似。

https://drive.google.com/open?id=1X1W-wctcP7SiYIOWx4VYTOh03zddF81r

2 个答案:

答案 0 :(得分:0)

您可以使用LEFT JOIN完成所需的操作。 MS Access使合并不同条件变得困难,因此这可能满足您的要求:

SELECT o.fk_OpeningTypeId, Count(oc.OpeningCityID) AS CountOfPosition
FROM tblOpening as o LEFT JOIN
     (SELECT oc.*
      FROM tblOpeningCity oc
      WHERE oc.OpeningCity IN ("Livermore", "Pleasanton")
     ) as oc
     ON oc.OpeningCityID = o.City
WHERE o.Position = "Flex Officer" AND
      o.Closed = No
GROUP BY o.fk_OpeningTypeId;

o上的过滤器可能正在删除您想要的内容。如果是这样,那么条件聚合将解决此问题:

SELECT o.fk_OpeningTypeId, 
       SUM(IIF(oc.OpeningCityID IS NOT NULL AND
               o.Position = "Flex Officer" AND
               o.Closed = No, 1, 0)
          ) AS CountOfPosition
FROM tblOpening as o LEFT JOIN
     (SELECT oc.*
      FROM tblOpeningCity oc
      WHERE oc.OpeningCity IN ("Livermore", "Pleasanton")
     ) as oc
     ON oc.OpeningCityID = o.City
GROUP BY o.fk_OpeningTypeId;

Access Database Sample

答案 1 :(得分:0)

只需使用这样的IIF()语句添加条件,然后在其周围加上Sum()

SELECT tblOpening.fk_OpeningTypeId
,Sum(IIF(tblOpening.Position = "YourCondition", 1, 0)) AS CountOfPosition
FROM tblOpeningCity
INNER JOIN tblOpening ON tblOpeningCity.OpeningCityID = tblOpening.City
WHERE (
    ((tblOpening.Position) = "Flex Officer")
    AND ((tblOpening.Closed) = No)
    AND (
        (tblOpeningCity.OpeningCity) = "Livermore"
        OR (tblOpeningCity.OpeningCity) = "Pleasanton"
        )
    )
GROUP BY tblOpening.fk_OpeningTypeId;