卡在一个复杂的查询中

时间:2019-11-03 20:33:39

标签: mysql sql

返回至少拥有2个不同订单的员工,其中订单上的某些产品的数量大于等于5

我尝试了group by和having子句,但未获得预期结果。我尝试了以下查询并对它进行了一些更改。

SELECT e.EmployeeId, e.EmployeeName, COUNT(op.OrderId) AS orderCount 
FROM db_order.Employee e
JOIN db_order.orders o ON e.EmployeeId = o.EmployeeId
JOIN db_order.orderedproduct op ON op.OrderId = o.OrderId
WHERE op.quantity >= 5
GROUP BY o.OrderId
HAVING orderCount > 1 

输出: 'E0002','E.爱德华兹,'2'

预期输出: E0006,D.Davis,2

2 个答案:

答案 0 :(得分:1)

使用两种聚合级别:

select employeeid
from (select o.employeeid, o.OrderId
      from db_order.orders o join
           db_order.orderedproduct op 
           on op.OrderId = o.OrderId
      where op.quantity > 5
      group by o.employeeid, o.orderid
     ) o
group by employeeid
having count(*) >= 2;

我将让您加入employee表以获得更多信息。

编辑:

您还可以通过COUNT(DISTINCT)和右键GROUP BY使用您的方法:

SELECT e.EmployeeId, e.EmployeeName,
       COUNT(DISTINCT op.OrderId) AS orderCount 
FROM db_order.Employee e JOIN
     db_order.orders o
     ON e.EmployeeId = o.EmployeeId JOIN 
     db_order.orderedproduct op
     ON op.OrderId = o.OrderId
WHERE op.quantity >= 5
GROUP BY e.EmployeeId, e.EmployeeName
HAVING orderCount > 1 ;

答案 1 :(得分:0)

计算具有2个以上订单且5个或更多项目的员工。

SELECT
    O.EmployeeId,
    COUNT(*)
FROM
    OrderedProduct OP
    INNER JOIN Orders O ON O.OrderId=OP.OrderId
WHERE
    OP.Quantity >= 5
GROUP BY
    O.EmployeeId
HAVING
    COUNT(*) >= 2