我有一个表格,我需要在其中获取每个类别的前 n 个最高数量的项目。
类别项目库存计数
------- ----- -------------
饮料牛奶3
饮料水2
饮料啤酒9
餐具叉 7
餐具勺 2
餐具刀 1
用具叉4
我想要的输出是最上面 2 个类别的最高库存。
类别项目库存计数
------- ----- -------------
饮料啤酒9
饮料牛奶3
餐具叉 7
用具叉4
最佳答案
这应该对你有用。如果它不满足您的要求,请回发您需要的内容。
您最初的愿望是有 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
关于sql - 访问组中的前 n 个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3481916/