SQL 查询 - 获取具有 Count() 的 Min() ID 的 SupplierName
SQL Query - Getting the SupplierName with the ID of a Min() of a Count()
我正在这个数据库中测试一个查询:
http://www.w3schools.com/sql/trysql.asp?filename=trysql_func_count
我想找出产品较少的供应商的名称。
产品table:
ProductID | ProductName | SupplierID | CategoryID | Unit| Price
供应商table:
SupplierID | SupplierName | ContactName | AddressCity | PostalCode | Country | Phone
到目前为止,我只得到了 SupplierID,它是 10,但是我在完成查询时遇到了问题,因此它可以 return 该 ID 的 SupplierName。
SELECT SupplierID AS SupID, min(MinSuppPrice)
FROM (
SELECT P.SupplierID, count(P.Price) MinSuppPrice
FROM Products P
group by P.SupplierID
);
提前致谢。
一个简单的方法使用解析函数:
SELECT SupplierID AS SupID, NumProducts
FROM (SELECT P.SupplierID, COUNT(*) as NumProducts,
DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
FROM Products P
GROUP BY P.SupplierID
) p
WHERE seqnum = 1;
我找到了查询的答案 "Find the name of the Supplier with the less Products."(和 SupplierID)
SELECT S.SupplierID, S.SupplierName
FROM Suppliers S, Products P
WHERE S.SupplierID = P.SupplierID
GROUP BY S.SupplierID, S.SupplierName
HAVING COUNT(P.ProductID) = (
SELECT MIN (ProdCounter)
FROM (
SELECT COUNT(P.ProductID) AS ProdCounter
FROM Products P
GROUP BY P.SupplierID
)
);
结果是:
SupplierID | SupplierName
10 Refrescos Americanas LTDA
13 Nord-Ost-Fisch Handelsgesellschaft mbH
27 Escargots Nouveaux
(他们在 Products table 中只有 1 个产品)
我正在这个数据库中测试一个查询: http://www.w3schools.com/sql/trysql.asp?filename=trysql_func_count
我想找出产品较少的供应商的名称。
产品table:
ProductID | ProductName | SupplierID | CategoryID | Unit| Price
供应商table:
SupplierID | SupplierName | ContactName | AddressCity | PostalCode | Country | Phone
到目前为止,我只得到了 SupplierID,它是 10,但是我在完成查询时遇到了问题,因此它可以 return 该 ID 的 SupplierName。
SELECT SupplierID AS SupID, min(MinSuppPrice)
FROM (
SELECT P.SupplierID, count(P.Price) MinSuppPrice
FROM Products P
group by P.SupplierID
);
提前致谢。
一个简单的方法使用解析函数:
SELECT SupplierID AS SupID, NumProducts
FROM (SELECT P.SupplierID, COUNT(*) as NumProducts,
DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
FROM Products P
GROUP BY P.SupplierID
) p
WHERE seqnum = 1;
我找到了查询的答案 "Find the name of the Supplier with the less Products."(和 SupplierID)
SELECT S.SupplierID, S.SupplierName
FROM Suppliers S, Products P
WHERE S.SupplierID = P.SupplierID
GROUP BY S.SupplierID, S.SupplierName
HAVING COUNT(P.ProductID) = (
SELECT MIN (ProdCounter)
FROM (
SELECT COUNT(P.ProductID) AS ProdCounter
FROM Products P
GROUP BY P.SupplierID
)
);
结果是:
SupplierID | SupplierName
10 Refrescos Americanas LTDA
13 Nord-Ost-Fisch Handelsgesellschaft mbH
27 Escargots Nouveaux
(他们在 Products table 中只有 1 个产品)