在 SQL 中一个一个地除以另一个

Divide one by another in SQL

我想我把这个复杂化了。

我不擅长SQL,所以我有时需要使用查询生成器。

我想要实现的目标:

我想让我的查询显示给我:

经理姓名

经理姓名出现在 table

中的次数

等于TRUE的争议数

争议除以经理在 table

中的总次数

当前SQL

SELECT DISTINCT tbl_Quality_Disputes.LoggedDate, tbl_Quality_Disputes.Manager, Count(tbl_Quality_Disputes.Manager) AS CountOfManager, [Decision]/[Manager] AS Success_Rate
    FROM tbl_Quality_Disputes
    GROUP BY tbl_Quality_Disputes.LoggedDate, tbl_Quality_Disputes.Manager, tbl_Quality_Disputes.Decision, [Decision]/[Manager]
    HAVING (((tbl_Quality_Disputes.Decision)="Approved"));

我哪里出错了?

提前致谢


尝试使用以下查询,

SELECT tbl_Quality_Disputes.LoggedDate, tbl_Quality_Disputes.Manager, 
Count(tbl_Quality_Disputes.Manager) AS CountOfManager, [Decision]/[Manager] AS Success_Rate
    FROM tbl_Quality_Disputes
WHERE tbl_Quality_Disputes.Decision="Approved"
    GROUP BY tbl_Quality_Disputes.LoggedDate, tbl_Quality_Disputes.Manager, 
tbl_Quality_Disputes.Decision, [Decision]/[Manager];

请提供示例数据和预期输出

让我们从您需要的分组开始。在您的结果中,您希望每个经理都有一行,就是这样,绝对没有 Decision.

那么,您没有对 WHERE 子句中的决策进行过滤是正确的,因为这也会从 count(*) 中删除行,但是 HAVING 是意味着聚合字段的条件,所以你也不能把它放在那里。由于您需要对其中一个聚合进行过滤而不是对另一个聚合进行过滤,因此您可以在需要的聚合内部使用 case

最后,成功率的计算应该基于计数,而不是ManagerDecision字段。

我忽略了 LoggedDate 字段,因为它的含义不明确,但如果你稍微解释一下,我会编辑我的查询,使其适合

SELECT  Manager,
        COUNT(*) AS CountOfManager,
        SUM(case when Decision = "Approved" then 1 else 0 end) AS Decision,
        SUM(case when Decision = "Approved" then 1 else 0 end) / Count(*) AS Success_Rate
FROM    tbl_Quality_Disputes
GROUP BY  Manager

作为旁注,我从所有字段前缀中删除了 table 名称,因为当使用单个 table 时不需要它并且使查询更加冗长。当使用两个或多个 tables 时,最好在列名前加上前缀,但您可以为 tables 提供别名以使一切更紧凑。

编辑

由于 LoggedDate 对于同一经理的所有行都是相同的,您可以添加到 GROUP BY 或使用 MIN 或 [=22 聚合它=](我更喜欢后一种选择,我觉得它更健壮)。

关于您遇到的错误,这可能是因为 Access doesn't support the CASE expression(抱歉,我不知道)。我用 IIF 替换了它,现在它可以工作了。

SELECT  Manager,
        MAX(LoggedDate) AS MaxLoggedDate,
        COUNT(*) AS CountOfManager,
        SUM(IIF(Decision = "Approved", 1, 0)) AS CountOfDecision,
        SUM(IIF(Decision = "Approved", 1, 0)) / Count(*) AS Success_Rate
FROM    tbl_Quality_Disputes
GROUP BY  Manager