我试图解决这个问题而且我已经到了这个
SELECT
c.CategoryID, p.ProductID,p.ProductName, COUNT(OrderID) TotalV
FROM
[Order Details] od
INNER JOIN
Products p ON od.ProductID = p.ProductID
INNER JOIN
Categories c ON c.CategoryID = p.CategoryID
INNER JOIN
(SELECT
t.CategoryID, MIN(TotalV) MinV
FROM
(SELECT
Categories.CategoryID, Products.ProductID,
COUNT(OrderID) TotalV
FROM
[Order Details]
JOIN
Products ON [Order Details].ProductID = Products.ProductID
JOIN
Categories ON Categories.CategoryID = Products.CategoryID
GROUP BY
Products.ProductID, Categories.CategoryID) t
GROUP BY
t.CategoryID) n ON c.CategoryID = n.CategoryID
GROUP BY
c.CategoryID, p.ProductID, MinV, p.ProductName
HAVING
COUNT(OrderID) = MinV
结果:
CategoryID | ProductID | ProductName | TotalV
-----------| ----------| ---------------------------| ------
1 | 67 | Laughing Lumberjack Lager | 10
2 | 15 | Genen Shouyu | 6
3 | 48 | Chocolade | 6
. . . .
. . . .
. . . .
我不确定这是否是一个好方法,因为我使用了两次:
SELECT
Categories.CategoryID,Products.ProductID, COUNT(OrderID) TotalV
FROM
[Order Details]
JOIN
Products ON [Order Details].ProductID = Products.ProductID
JOIN
Categories ON Categories.CategoryID = Products.CategoryID
GROUP BY
Products.ProductID, Categories.CategoryID
所以我认为可以有更好的方法来执行这个问题,任何帮助?