给出销售超过10家供应商产品的员工姓名
Give the names of employees who sell the products of more than 10 suppliers
我发现很难为上述问题编写查询我已经编写了以下查询但它返回了所有行
SELECT e.EmployeeID
FROM employees e
JOIN orders o ON e.EmployeeID = o.EmployeeID
JOIN order_details od ON o.OrderID = od.OrderID
JOIN Products p ON od.ProductID = p.ProductID
GROUP BY e.EmployeeID
HAVING COUNT(p.SupplierID) > 10
您的筛选条件是:
HAVING COUNT(p.SupplierID) > 10
COUNT()
计算非 NULL
值的数量。据推测,所有产品都有一个供应商,而您正在使用内部联接。因此,所有匹配的行都会被计算在内。相当于:
HAVING COUNT(*) > 10
这会计算给定员工的订单行数。
您想统计 个不同的 个供应商,而不是订单行。最简单的方法是使用 COUNT(DISTINCT)
:
HAVING COUNT(DISTINCT p.SupplierID) > 10
因为你正在学习SQL,建议你也看懂这个版本:
SELECT e.EmployeeID
FROM (SELECT e.EmployeeID, p.SupplierID, COUNT(*) as num_ordelines
FROM employees e JOIN
orders o
ON e.EmployeeID = o.EmployeeID JOIN
order_details od
ON o.OrderID = od.OrderID JOIN
Products p
ON od.ProductID = p.ProductID
GROUP BY e.EmployeeID, p.SupplierId
) es
GROUP BY EmployeeID
HAVING COUNT(SupplierID) > 10
这 returns 相同的结果集(假设 SupplierId
永远不会是 NULL
)。子查询每个 employee/supplier 有一行。然后外部查询计算这些行。
我发现很难为上述问题编写查询我已经编写了以下查询但它返回了所有行
SELECT e.EmployeeID
FROM employees e
JOIN orders o ON e.EmployeeID = o.EmployeeID
JOIN order_details od ON o.OrderID = od.OrderID
JOIN Products p ON od.ProductID = p.ProductID
GROUP BY e.EmployeeID
HAVING COUNT(p.SupplierID) > 10
您的筛选条件是:
HAVING COUNT(p.SupplierID) > 10
COUNT()
计算非 NULL
值的数量。据推测,所有产品都有一个供应商,而您正在使用内部联接。因此,所有匹配的行都会被计算在内。相当于:
HAVING COUNT(*) > 10
这会计算给定员工的订单行数。
您想统计 个不同的 个供应商,而不是订单行。最简单的方法是使用 COUNT(DISTINCT)
:
HAVING COUNT(DISTINCT p.SupplierID) > 10
因为你正在学习SQL,建议你也看懂这个版本:
SELECT e.EmployeeID
FROM (SELECT e.EmployeeID, p.SupplierID, COUNT(*) as num_ordelines
FROM employees e JOIN
orders o
ON e.EmployeeID = o.EmployeeID JOIN
order_details od
ON o.OrderID = od.OrderID JOIN
Products p
ON od.ProductID = p.ProductID
GROUP BY e.EmployeeID, p.SupplierId
) es
GROUP BY EmployeeID
HAVING COUNT(SupplierID) > 10
这 returns 相同的结果集(假设 SupplierId
永远不会是 NULL
)。子查询每个 employee/supplier 有一行。然后外部查询计算这些行。