SQL 4个表inner join 取值也为Nulls?

SQL 4 tables inner join pick up sum Nulls also?

我有 4 tables.... 员工、客户、订单和 Order_Info。我正在尝试内部加入 4 tables 来总结订单金额并根据 7% 计算员工佣金。我非常接近解决这个问题,但我有一个小问题:我没有得到所有的员工,因为出现的人数少于我的员工table。这就是我目前编写查询的方式:

SELECT Employees.lName, Employees.fName,
       SUM(quantOrdered * costEach) AS ttl_orders_value,
       (SUM(quantOrdered * costEach) * .07) AS Commission
FROM Customers
INNER JOIN Employees ON Customers.empNumber = Employees.empNumber 
INNER JOIN Orders ON Customers.custNumber = Orders.custNumber 
INNER JOIN Order_Info ON Orders.ordNumber = Order_Info.ordNumber
GROUP BY Employees.lName, Employees.fName 
ORDER BY Employees.lName, Employees.fName

我希望得到所有员工,即使他们的佣金和总销售额为零,我认为这是从 NULLS 计算的。

如果能帮助我改进查询,我们将不胜感激!

试试这个:

SELECT Employees.lName, Employees.fName,
       SUM(ISNULL(quantityOrdered,0) * ISNULL(priceEach,0)) AS ttl_orders_value,
       (SUM(ISNULL(quantOrdered,0) * ISNULL(costEach,0)) * .05) AS Commission
FROM Employees 
LEFT JOIN Customers ON Customers.empNumber = Employees.empNumber 
LEFT JOIN Orders 
   INNER JOIN OrderDetails ON Orders.ordNumber = OrderDetails.ordNumber
ON Customers.custNumber = Orders.custNumber
WHERE Employees.workTitle = 'Developer' 
GROUP BY Employees.lName, Employees.fName 
ORDER BY Employees.lName, Employees.fName

请注意,我已将 INNER JOIN 更改为 LEFT JOIN 仅适用于订单 table 因为正如您所说,员工记录应该存在,他们只是可能没有链接订单。

您可能还需要用 ISNULL([field_name], 0) 包装 NULL priceEach、costEach、quantityOrdered 和 quantOrdered 值,以便为那些没有任何订单的员工获得正确的结果。