我被困在sql查询上

问题描述 投票:-1回答:3

编写查询以列出不同的办事处(他们的地址),该办公室的雇员人数以及该办事处的雇员为销售代表的订单数量。

到目前为止,这是我在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

这里也是我用于参考的数据模型的链接。我知道我的代码并不完全正确,但我仍然坚持如何以一种有意义的方式将所有表连接在一起,所以任何帮助都会受到赞赏,谢谢!

mysql sql select join
3个回答
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;

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

0
投票

在多个表中聚合时,您可能会得到不正确的结果。在这里,你需要计算distinct员工orchewise计数将被订单数量夸大。请注意,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
© www.soinside.com 2019 - 2024. All rights reserved.