你可以試試嗎?我認爲它正在做正確的工作,因爲您正在查詢表中的MAX(COUNT),並且我認爲它會返回計數最高的值。
select S.SupplierName, R.count
from Suppliers S
LEFT JOIN (
select SupplierName, count(SupplierName) as count
from
Products as p
inner join
Suppliers as s
on p.SupplierID = s.SupplierID
group by SupplierName
) R
ON R.SupplierName = S.SupplierName
ORDER BY S.SupplierName
但是,您的原始問題「哪種產品最被買了?」,我會使用此查詢:
SELECT p.productname, od.ProductId, SUM(Quantity)
FROM [OrderDetails] od
JOIN Products P
ON od.ProductId = P.productId
GROUP BY od.ProductId, P.Productname
ORDER BY SUM(Quantity) DESC
由於供應商供應的材料,並沒有涉及到已售出的商品。顧客是買的。但是,問題只關注以最高數量銷售的產品類型 - 這可以從訂單明細表中找到,如果您將其與產品表一起加入,則可以命名所有銷售的產品以及銷售數量。
UPDATE
而對於誰提供大部分產品的供應商,我會使用這樣的:
SELECT P.SupplierId, S.SupplierName, COUNT(P.SupplierID)
FROM Products P
JOIN Suppliers S
ON S.SupplierId = P.SupplierId
GROUP BY P.SupplierId, S.SupplierName
ORDER BY COUNT(P.SupplierId) DESC
LIMIT 1
LIMIT 1(以MSSQL略有不同 - SELECT TOP 1 ...
)將確保您獲得最重要的結果。但是,如果供應商的供應商數量相同,那麼您必須將最大數量存儲在單獨的變量或查詢中。作爲使用變量W3Schools的託管網站都沒有要走的路,這裏有一個查詢,可以做同樣的工作就好了:
SELECT S.SupplierName, t.TotalCount
FROM Suppliers S
JOIN
( SELECT P.SupplierId, S.SupplierName, COUNT(P.SupplierID) as TotalCount
FROM Products P
JOIN Suppliers S
ON S.SupplierId = P.SupplierId
GROUP BY P.SupplierId, S.SupplierName) t
ON t.SupplierId = S.SupplierId
JOIN
( SELECT SupplierId, SupplierName, MAX(TotalCount) as Maximum
FROM
(SELECT P.SupplierId, S.SupplierName, COUNT(P.SupplierID) as TotalCount
FROM Products P
JOIN Suppliers S
ON S.SupplierId = P.SupplierId
GROUP BY P.SupplierId, S.SupplierName) t2
) t3
ON t3.Maximum = t.TotalCount
WHERE t.TotalCount = t3.Maximum
ORDER BY t.TotalCount DESC
因爲你已經張貼在你原來的問題基本上是一樣的,所以它沒有什麼幫助......:如果它是一個「現實生活」的例子,你可以引入一個變量來幫助整理查詢。基本上,你分配了我在上面第二次連接中使用的查詢的結果,並且你只是在where子句中引用它。
還有更多的變數在這裏:http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
SET @max = (SELECT MAX(TotalCount) as Maximum
FROM
( SELECT P.SupplierId, S.SupplierName, COUNT(P.SupplierID) as TotalCount
FROM Products P
JOIN Suppliers S
ON S.SupplierId = P.SupplierId
GROUP BY P.SupplierId, S.SupplierName) t);
SELECT S.SupplierName, t.TotalCount
FROM Suppliers S
JOIN
( SELECT P.SupplierId, S.SupplierName, COUNT(P.SupplierID) as TotalCount
FROM Products P
JOIN Suppliers S
ON S.SupplierId = P.SupplierId
GROUP BY P.SupplierId, S.SupplierName) t
ON t.SupplierId = S.SupplierId
WHERE t.TotalCount = @max
ORDER BY t.TotalCount DESC
哪些DBMS您使用的? Postgres的?甲骨文? – 2014-08-31 14:33:05
「*但是這樣我創建了一個全新的表*」 - 在你的例子中沒有'create table'語句。你爲什麼認爲'select'創建一個新表? – 2014-08-31 14:34:01
我剛剛查看了數據庫,'產品'表包含'supplierID',表明供應商正在銷售什麼產品。關於哪個供應商已經購買了什麼產品沒有存儲在該數據庫中的信息。 – 2014-08-31 14:36:38