我被困在sql查询上

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我被困在sql查询上相关的知识,希望对你有一定的参考价值。

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

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

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

答案

你可以实现如下:

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;
另一答案

你可以试试以下

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
另一答案

在多个表中聚合时,您可能会得到不正确的结果。在这里,你需要计算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

以上是关于我被困在sql查询上的主要内容,如果未能解决你的问题,请参考以下文章

我被困在运行 gradle 任务“assembledebug”

我被困在递归地实现基数排序

我试图捕捉刷卡的输入,但我被困在使用 C# Windows 窗体

我被困在从 JSON API 获取数据中,它有点复杂和嵌套,我想从“abilities”数组中获取“resource_uri”

我试图通过在线课程学习在shell(jupyter notebook)/(anaconda提示符)中使用python中的元组。我被困在元组部分

行项目表的总和 SQL 子查询