我有4个表......员工,客户,订单和Order_Info。我正在尝试内部加入4个表来总结订单金额并根据7%计算员工佣金。我非常接近解决这个问题,但我有一个小问题:我没有得到所有员工,因为我的员工表中存在的数量少于存在。这就是我目前编写查询的方式:
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计算的。
任何帮助改进我的查询将不胜感激!
答案 0 :(得分:2)
试试这个:
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更改为仅用于Orders表的LEFT JOIN,因为正如您所说的Employees记录应该在那里,它们可能没有链接的订单。
您可能还需要使用ISNULL([field_name],0)包装NULL priceEach,costEach,quantityOrdered和quantOrdered值,以便为没有任何订单的员工获取正确的结果。