写一个查询,列出不同的办公室(他们的地址),该办公室员工人数以及该办公室员工为销售代表的订单数量。
到目前为止,这是我在mysql中提出的:
SELECT Offices.addressLine1,
Offices.addressLine2,
COUNT(Employees.employeeNumber),
COUNT(Orders.orderNumber)
FROM Offices,
Employees,
Customers,
Orders
WHERE Offices.officeCode=Employees.officeCode AND
Employees.employeeNumber=Customers.salesRepEmployeeNumber AND
Customers.customerNumber=Orders.customerNumber
GROUP BY addressLine1;
http://www.richardtwatson.com/dm6e/images/general/ClassicModels.png
这里也是我用于参考的数据模型的链接。我知道我的代码并不完全正确,但我仍然坚持如何以一种有意义的方式将所有表连接在一起,所以任何帮助都会受到赞赏,谢谢!
答案 0 :(得分:0)
您可以按照以下方式实现:
SELECT o.officecode
,o.addressLine1
,o.addressLine2
,count(e.employeeNumber)
,SUM(CASE
WHEN o.orderNumber IS NOT NULL
THEN 1
ELSE 0
END) AS TotalOrders
FROM Offices AS o
INNER JOIN Employees AS e ON o.officecode = e.officecode
LEFT JOIN Customers AS c ON c.salesRepEmployeeNumber = e.employeeNumber
INNER JOIN Orders AS o ON o.customerNumber = c.customerNumber
GROUP BY o.officecode
,o.addressLine1
,o.addressLine2;
答案 1 :(得分:0)
您可以尝试使用以下
SELECT
Offices.officeCode,
Offices.addressLine1,
Offices.addressLine2,
COUNT(ISNULL(Employees.employeeNumber,0)) AS EmpCount,
COUNT(ISNULL(Orders.OrderNumber,0)) AS NoOfOrders
FROM
Offices
INNER JOIN Employees
ON Offices.officeCode = Employees.officeCode
LEFT JOIN Customers
ON Employees.employeeNumber = Customers.salesRepEmployeeNumber
LEFT JOIN Orders
ON Customers.customerNumber = Orders.customerNumber
GROUP BY
Offices.officeCode,
Offices.addressLine1,
Offices.addressLine2
答案 2 :(得分:0)
在多个表中聚合时,您可能会得到不正确的结果。在这里,您需要计算distinct
名员工,或者计数会被订单数量夸大。请注意,count函数会忽略NULL,因此无需补偿NULL,但您需要在custome / / orders上进行左连接以确保所有员工都被计算在内。
SELECT
o.officecode
, o.addressLine1
, o.addressLine2
, count(distinct e.employeeNumber)
, count(o.orderNumber) AS TotalOrders
FROM Offices AS o
INNER JOIN Employees AS e ON o.officecode = e.officecode
LEFT JOIN Customers AS c ON c.salesRepEmployeeNumber = e.employeeNumber
LEFT JOIN Orders AS o ON o.customerNumber = c.customerNumber
GROUP BY
o.officecode
, o.addressLine1
, o.addressLine2