访问组中的前n个

时间:2010-08-14 03:44:53

标签: sql ms-access-2007

我有一张桌子,我需要为每个类别获得前n个最高金额的项目。

Category Item  InventoryCount
-------  ----- ------------- 
Beverage  milk    3  
Beverage  water   2 
Beverage  beer    9 
Utensil   fork    7 
Utensil   spoon   2 
Utensil   knife   1 
Utensil   spork   4 

我想要的输出是最高2个类别的最高库存。

Category Item  InventoryCount
-------  ----- ------------- 
Beverage  beer   9 
Beverage  milk   3 
Utensil   fork   7 
Utensil  spork   4 

2 个答案:

答案 0 :(得分:8)

这对你有用。如果它不符合您的要求,请回复您需要的内容。 你最初的愿望是拥有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

答案 1 :(得分:-4)

如果订单不重要:

SELECT * FROM inv
ORDER BY InventoryCount DESC LIMIT 5