Access 2010 SQL select top with a additional field

时间:2013-11-25 16:03:55

标签: sql select subquery grouping ms-access-2010

通过支出,我获得了前五大类别/年组合:

SELECT TOP 3 [Category],
             SUM([Spending]),
             Year
FROM Data
GROUP BY [Category], [Year]
;

我想看看每年的前五大类别。

e.g。如果3年期间的最高支出类别是A,B,C(但不是D),我想输出:

  Category   Total Spending   Year
  A          123              1  
  A          321              2
  A          987              3
  B          798              1
  B          465              2 
  B          153              3
  C          654              1
  C          486              2
  C          759              3

这是在这里解决的,但只有两个字段 - SQL: Select Top 3 Records + Sum of Quantity

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

SELECT [Category], SUM([Spending]) as TotalSpending, Year
FROM Data
WHERE Year IN (SELECT TOP 5 Year FROM Data ORDER BY Year DESC)
GROUP BY [Category], [Year]
ORDER BY SUM([Spending])  DESC, [Year] DESC