MYSQL sum/Count 内部加入组失败

MYSQL sum/Count fails inside inner join group by

我有一个 table 包含销售记录:

Sale ID EmployeeId(FK) Employee 2 ...
1 101 Null ...
2 102 Null ...
3 300 Bob ...
... ... ... ...

我有另一个包含员工记录的 table:

EmployeeId EmployeeName ...
101 Amanda ...
102 Bob ...
... ... ...
300 cicilia ...
... ... ...

我正在尝试做一个 select,我在其中获取所有销售额并按员工对它们进行分组以进行绩效分析。到目前为止,我设法弄清了员工及其销售数量和总数。问题是我的销售记录中的第三列称为 employee2,它可以为空,因为并非每个销售都有另一个员工协助。与第二列不同,它没有索引到员工 table。

因此,例如在我下面的查询中,预期结果应该是 Amanda 有 1 个销售计数,0 个帮助计数,同时 Boss 有 1 个销售计数,1 个帮助计数,cicillia 有 1 个销售计数,0 个帮助计数。但是我得到的所有正确的销售计数都是 1,但是鲍勃的帮助计数是 0。到目前为止,这是我的查询:

select employee.employee_id, 
       employee.employee_Name, 
       count(sale.sale_id) as saleCount, 
       sum(sale.grand_total) as totalSalesRevenue, 
       sum(CASE WHEN sale.employee2 = employee.employee_Name THEN 1 
                ELSE 0 END) as helperEmpCount
from employee 
inner join sale on employee.employee_id = sale.employee_id 
group by employee.employee_id;

结果集,其中helpCounts不应该为0。 我 运行 一个 mysql 8.0 数据库。

编辑:我找到了一种解决方法,尽管效率很低。如果我将我的计数更改为嵌套 select 它会起作用,但考虑到我有很多员工,这会大大降低性能。

新查询:

select employee.employee_id, 
       employee.employee_Name, 
       count(sale.sale_id) as saleCount, 
       sum(sale.grand_total) as totalSalesRevenue, 
       (select count(sale.employee2) from sale where sale.employee2= employee_Name) as helperEmpCount
from employee 
inner join sale on employee.employee_id = sale.employee_id 
group by employee.employee_id;

知道如何提高效率吗?

您可以根据 2 个条件中的任何一个加入表并使用条件聚合:

SELECT e.employee_id, 
       e.employee_Name, 
       SUM(s.employee_id = e.employee_id) AS saleCount, 
       SUM(CASE WHEN s.employee_id = e.employee_id THEN s.grand_total ELSE 0 END) AS totalSalesRevenue, 
       SUM(s.employee2 = e.employee_Name) AS helperEmpCount
FROM employee e LEFT JOIN sale s
ON s.employee_id = e.employee_id OR s.employee2 = e.employee_Name
GROUP BY e.employee_id;