退回至少有2个不同订单的员工,其中订单上的某些产品的数量> = 5。
* Format:
* EmployeeId, EmployeeName, orderCount
到目前为止我写过:
ResultSet rst = stmt.executeQuery("SELECT Employee.EmployeeId,EmployeeName, COUNT(DISTINCT Orders.EmployeeId) as orderCount "
+ "FROM Employee,Orders,OrderedProduct"
+ " WHERE quantity >=5 AND Employee.EmployeeId = Orders.EmployeeId AND Orders.OrderId = OrderedProduct.OrderId"
+ " GROUP BY OrderedProduct.OrderId,Employee.EmployeeId,EmployeeName");
我得到了结果:
EmployeeId, EmployeeName, orderCount
E0002, E. Edwards, 1
E0007, I. Irvin, 1
E0006, D. Davis, 1
E0001, B. Bogart, 1
E0006, D. Davis, 1
但我正在寻找的是
OrderId, EmployeeId, EmployeeName, orderCount
E0006, D. Davis, 2
我无法弄清楚如何计算D.戴维斯两次,真的很感激一些帮助
答案 0 :(得分:1)
您应该过滤添加HAVING COUNT(DISTINCT Orders.EmployeeId) > 1
ResultSet rst = stmt.executeQuery("SELECT Employee.EmployeeId, EmployeeName, COUNT(DISTINCT Orders.OrderId) as orderCount "
+ " FROM Employee,Orders,OrderedProduct"
+ " WHERE quantity >=5 AND Employee.EmployeeId = Orders.EmployeeId AND Orders.OrderId = OrderedProduct.OrderId"
+ " GROUP BY Employee.EmployeeId,EmployeeName"
+ " HAVING COUNT(DISTINCT Orders.OrderId) >1 ");
答案 1 :(得分:0)
首先,从不在FROM
子句中使用逗号。 始终使用正确的,明确的JOIN
语法。对于此查询,您可以执行以下操作:
SELECT e.EmployeeId, e.EmployeeName, COUNT(DISTINCT o.OrderId) as orderCount
FROM Employee e JOIN
Orders o
ON e.EmployeeId = o.EmployeeId JOIN
OrderedProduct op
ON o.OrderId = op.OrderId
GROUP BY e.EmployeeId, e.EmployeeName
HAVING COUNT(DISTINCT o.OrderId) > 1 AND MAX(quantity) >= 5;
你应该明白这是如何运作的。要计算订单,您需要计算OrderId
秒。 <{1}}上的条件必须在 quantity
之后发生。