1

我正在尝试编写一个 SQL 查询来显示每个类别的总和。问题是我需要每个类别的总和,即使总和为零,它仍然应该显示结果。

我通过使用 DAL 层来执行此操作,因此通过 C# 并且我使用的是 access 2010 数据库。

这是我当前的工作查询:

SELECT        SUM(f.bedrag) AS totaal, c.omschrijving, Limiet.maximumBedrag
FROM            ((Financien f INNER JOIN
                         Categorie c ON f.categorieId = c.id) INNER JOIN
                         Limiet ON f.limietId = Limiet.id)
WHERE        (f.inkomstOfUitgave = 1)
GROUP BY f.categorieId, c.omschrijving, Limiet.maximumBedrag

现在在 SUM 函数之上,我还需要检查空值,如果一个类别的总和为 0,它应该显示 0。现在所有为 0 的结果都被过滤掉了,但我必须看到它们。

有人知道如何解决吗?我试过了IsNull()NZ但我无法让它工作。这是查询结果的屏幕截图。

如您所见,我得到两个结果,但如果查询显示总和 0 结果,我应该得到 7。

有人知道如何解决这个问题吗?

4

2 回答 2

1

If the question is about how to display Null as 0 in an Access query, consider this simple query. It returns some rows with Null in the SumOfbedrag column.

SELECT y.categorieId, Sum(y.bedrag) AS SumOfbedrag
FROM YourTable AS y
GROUP BY y.categorieId

Using that SQL as a subquery, the containing query can transform Null to 0 with an IIf() expression.

SELECT
    sub.categorieId,
    IIf(sub.SumOfbedrag Is Null, 0, sub.SumOfbedrag) AS totaal
FROM
    (
        SELECT y.categorieId, Sum(y.bedrag) AS SumOfbedrag
        FROM YourTable AS y
        GROUP BY y.categorieId
    ) AS sub;

However, looking at your screenshot again makes me think the issue is actually that your query does not include rows with Null in the totaal column. In that case, examine the underlying data before you aggregate it with GROUP BY. See whether this query returns any rows ...

SELECT f.bedrag, c.omschrijving, Limiet.maximumBedrag
FROM
    (Financien f
    INNER JOIN Categorie c
    ON f.categorieId = c.id)
    INNER JOIN Limiet
    ON f.limietId = Limiet.id
WHERE
        f.inkomstOfUitgave = 1
    AND f.bedrag Is Null

If that query returns no rows, my best guess is that one or both of your joins should be changed from INNER to LEFT JOIN or RIGHT JOIN.

于 2013-04-13T15:44:18.820 回答
0

还显示 0 值的答案是:答案是由“drch”做出的,为此我非常感谢他!:)

SUM(IIF(IsNULL(f.bedrag), 0, f.bedrag)) AS bedrag

那里还有很多其他的问题,这是完整的查询:

SELECT        c.omschrijving as Omschrijving, SUM(IIF(IsNULL(f.bedrag), 0, f.bedrag)) AS bedrag, l.maximumBedrag as maximumBedrag
FROM            ((Categorie c LEFT OUTER JOIN
                         Financien f ON f.categorieId = c.id) LEFT OUTER JOIN
                         Limiet l ON l.categorieId = c.id)
WHERE        (f.inkomstOfUitgave IS NULL) OR
                         (f.inkomstOfUitgave = 1)
GROUP BY c.id, f.categorieId, c.omschrijving, l.maximumBedrag
于 2013-04-14T15:33:12.150 回答