这应该适合你。如果它不满足您的要求,请发回您需要的内容。
您最初的愿望是拥有 25 个,因此您只需将最后一个子句修改为 HAVING COUNT(*) <= 25
SELECT a.item,
a.category,
a.inventorycount,
COUNT(*) AS ranknumber
FROM inv AS a
INNER JOIN inv AS b
ON (a.category = b.category)
AND (a.inventorycount <= b.inventorycount)
GROUP BY a.category,
a.item,
a.inventorycount
HAVING COUNT(*) <= 2
ORDER BY a.category, COUNT(*) DESC
如果您想从表中选择更多列,只需将它们添加到 SELECT 和 `GROUP BY' 子句。
只有当您想扩展“TOP n for each Category, foo, bar”时,您才会将这些列添加到INNER JOIN 子句中。
--show the top 2 items for each category and year.
SELECT a.item,
a.category,
a.year,
a.inventorycount,
COUNT(*) AS ranknumber
FROM inv AS a
INNER JOIN inv AS b
ON (a.category = b.category)
AND (a.year = b.year)
AND (a.inventorycount <= b.inventorycount)
GROUP BY a.category, a.item, a.year, a.inventorycount
HAVING COUNT(*) <= 2
ORDER BY a.year, a.category, COUNT(*) DESC